@moku-labs/common 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.cjs ADDED
@@ -0,0 +1,1023 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region \0rolldown/runtime.js
3
+ var __defProp = Object.defineProperty;
4
+ var __exportAll = (all, no_symbols) => {
5
+ let target = {};
6
+ for (var name in all) __defProp(target, name, {
7
+ get: all[name],
8
+ enumerable: true
9
+ });
10
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
11
+ return target;
12
+ };
13
+ //#endregion
14
+ let _moku_labs_core = require("@moku-labs/core");
15
+ let node_fs = require("node:fs");
16
+ //#region src/plugins/log/expect.ts
17
+ /**
18
+ * Named error thrown by `expect()` assertions when a trace condition fails.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * throw new LogExpectAssertionError("missing event build:complete");
23
+ * ```
24
+ */
25
+ var LogExpectAssertionError = class extends Error {
26
+ /**
27
+ * Construct a new assertion error with a descriptive failure message.
28
+ *
29
+ * @param message - Descriptive failure message (event name, partial, index).
30
+ * @example
31
+ * ```ts
32
+ * throw new LogExpectAssertionError("missing event build:complete");
33
+ * ```
34
+ */
35
+ constructor(message) {
36
+ super(message);
37
+ this.name = "LogExpectAssertionError";
38
+ }
39
+ };
40
+ /**
41
+ * Tests whether a value is a non-null, non-array plain object.
42
+ *
43
+ * @param value - The value to test.
44
+ * @returns `true` when `value` is a non-null object that is not an array.
45
+ * @example
46
+ * ```ts
47
+ * isPlainObject({ a: 1 }); // true
48
+ * isPlainObject([1]); // false
49
+ * ```
50
+ */
51
+ function isPlainObject$1(value) {
52
+ return typeof value === "object" && value !== null && !Array.isArray(value);
53
+ }
54
+ /**
55
+ * Tests whether `actual` is an array that recursively matches every element of
56
+ * the `partial` array (element-wise, with equal length).
57
+ *
58
+ * @param actual - The value to test against (must be an array of equal length).
59
+ * @param partial - The expected partial array shape.
60
+ * @returns `true` when `actual` is an equal-length array matching `partial` element-wise.
61
+ * @example
62
+ * ```ts
63
+ * matchesPartialArray([1, 2], [1, 2]); // true
64
+ * matchesPartialArray([1], [1, 2]); // false (length mismatch)
65
+ * ```
66
+ */
67
+ function matchesPartialArray(actual, partial) {
68
+ if (!Array.isArray(actual) || actual.length !== partial.length) return false;
69
+ return partial.every((value, index) => matchesPartial(actual[index], value));
70
+ }
71
+ /**
72
+ * Tests whether `actual` is a plain object in which every `partial` key
73
+ * recursively matches (extra `actual` keys are ignored).
74
+ *
75
+ * @param actual - The value to test against (must be a plain object).
76
+ * @param partial - The expected partial object shape.
77
+ * @returns `true` when every `partial` key exists in `actual` and matches recursively.
78
+ * @example
79
+ * ```ts
80
+ * matchesPartialObject({ a: 1, b: 2 }, { a: 1 }); // true
81
+ * matchesPartialObject({ a: 1 }, { b: 1 }); // false (missing key)
82
+ * ```
83
+ */
84
+ function matchesPartialObject(actual, partial) {
85
+ if (!isPlainObject$1(actual)) return false;
86
+ return Object.keys(partial).every((key) => key in actual && matchesPartial(actual[key], partial[key]));
87
+ }
88
+ /**
89
+ * Subset-equality matcher: is `partial` a recursive subset of `actual`?
90
+ *
91
+ * Fast path via `Object.is` (covers identical primitives/references and
92
+ * `null`/`NaN`); primitives compare with `Object.is`; arrays match element-wise
93
+ * with equal length; plain objects require every `partial` key to recursively
94
+ * match (extra `actual` keys ignored).
95
+ *
96
+ * @param actual - The value to test against (typically `entry.data`).
97
+ * @param partial - The expected partial shape.
98
+ * @returns `true` when `partial` is a recursive subset of `actual`.
99
+ * @example
100
+ * ```ts
101
+ * matchesPartial({ a: 1, b: 2 }, { a: 1 }); // true
102
+ * matchesPartial([1, 2], [1]); // false (length mismatch)
103
+ * ```
104
+ */
105
+ function matchesPartial(actual, partial) {
106
+ if (Object.is(actual, partial)) return true;
107
+ if (Array.isArray(partial)) return matchesPartialArray(actual, partial);
108
+ if (isPlainObject$1(partial)) return matchesPartialObject(actual, partial);
109
+ return false;
110
+ }
111
+ /**
112
+ * Tests whether an entry matches `event` and (when provided) `partial`.
113
+ *
114
+ * @param entry - The candidate trace entry.
115
+ * @param event - Required event name.
116
+ * @param partial - Optional partial data shape (subset-matched against `entry.data`).
117
+ * @returns `true` when the entry matches the event and optional partial.
118
+ * @example
119
+ * ```ts
120
+ * entryMatches({ level: "info", event: "a", data: { x: 1 }, ts: 0 }, "a", { x: 1 }); // true
121
+ * ```
122
+ */
123
+ function entryMatches(entry, event, partial) {
124
+ if (entry.event !== event) return false;
125
+ return partial === void 0 ? true : matchesPartial(entry.data, partial);
126
+ }
127
+ /**
128
+ * Render a `partial` for an error message, prefixed with a space when present.
129
+ *
130
+ * @param partial - Optional partial data shape.
131
+ * @returns A ` matching <json>` suffix, or an empty string when absent.
132
+ * @example
133
+ * ```ts
134
+ * describePartial({ ok: true }); // ' matching {"ok":true}'
135
+ * ```
136
+ */
137
+ function describePartial(partial) {
138
+ return partial === void 0 ? "" : ` matching ${JSON.stringify(partial)}`;
139
+ }
140
+ /**
141
+ * Find the first entry with `event` at or after `startIndex`, scanning forward.
142
+ *
143
+ * @param entries - The trace array to scan.
144
+ * @param event - Event name to find.
145
+ * @param startIndex - Index to begin scanning from (inclusive).
146
+ * @returns The index of the first match, or `-1` when none exists from `startIndex` on.
147
+ * @example
148
+ * ```ts
149
+ * findEventAtOrAfter([{ event: "a" }, { event: "b" }] as LogEntry[], "b", 0); // 1
150
+ * ```
151
+ */
152
+ function findEventAtOrAfter(entries, event, startIndex) {
153
+ for (let index = startIndex; index < entries.length; index++) if (entries[index]?.event === event) return index;
154
+ return -1;
155
+ }
156
+ /**
157
+ * Create a fluent assertion chain bound to the live `entries` array. Each method
158
+ * reads `entries` at call time, so assertions reflect later logging.
159
+ *
160
+ * @param entries - The live trace array (read on each assertion call).
161
+ * @returns A fresh {@link ExpectChain} backed by `entries`.
162
+ * @example
163
+ * ```ts
164
+ * createExpectChain(state.entries).toHaveEvent("build:complete");
165
+ * ```
166
+ */
167
+ function createExpectChain(entries) {
168
+ const chain = {
169
+ /**
170
+ * Assert at least one entry has `event`, optionally matching `partial`.
171
+ *
172
+ * @param event - Event name to find.
173
+ * @param partial - Optional partial data shape (subset-matched).
174
+ * @returns The same chain for chaining.
175
+ * @throws {LogExpectAssertionError} When no matching entry exists.
176
+ * @example
177
+ * ```ts
178
+ * chain.toHaveEvent("build:phase", { status: "start" });
179
+ * ```
180
+ */
181
+ toHaveEvent(event, partial) {
182
+ if (!entries.some((entry) => entryMatches(entry, event, partial))) throw new LogExpectAssertionError(`Expected trace to contain event "${event}"${describePartial(partial)}, but none was found.`);
183
+ return chain;
184
+ },
185
+ /**
186
+ * Assert all of `events` appear in the trace in the given relative order.
187
+ *
188
+ * @param events - Ordered list of event names (gaps allowed).
189
+ * @returns The same chain for chaining.
190
+ * @throws {LogExpectAssertionError} When the ordering cannot be satisfied.
191
+ * @example
192
+ * ```ts
193
+ * chain.toHaveEventInOrder(["build:phase", "build:complete"]);
194
+ * ```
195
+ */
196
+ toHaveEventInOrder(events) {
197
+ let cursor = 0;
198
+ for (const [position, event] of events.entries()) {
199
+ const matchIndex = findEventAtOrAfter(entries, event, cursor);
200
+ if (matchIndex === -1) throw new LogExpectAssertionError(`Expected events in order ${JSON.stringify(events)}, but "${event}" (index ${position}) was not found at or after position ${cursor}.`);
201
+ cursor = matchIndex + 1;
202
+ }
203
+ return chain;
204
+ },
205
+ /**
206
+ * Assert NO entry has `event` (optionally narrowed by `partial`).
207
+ *
208
+ * @param event - Event name that must be absent.
209
+ * @param partial - Optional partial data shape; only matching entries violate.
210
+ * @returns The same chain for chaining.
211
+ * @throws {LogExpectAssertionError} When a matching entry exists.
212
+ * @example
213
+ * ```ts
214
+ * chain.toNotHaveEvent("deploy:failed");
215
+ * ```
216
+ */
217
+ toNotHaveEvent(event, partial) {
218
+ const offending = entries.findIndex((entry) => entryMatches(entry, event, partial));
219
+ if (offending !== -1) throw new LogExpectAssertionError(`Expected trace to NOT contain event "${event}"${describePartial(partial)}, but found one at index ${offending}.`);
220
+ return chain;
221
+ }
222
+ };
223
+ return chain;
224
+ }
225
+ //#endregion
226
+ //#region src/plugins/log/api.ts
227
+ /**
228
+ * @file log plugin — API factory.
229
+ *
230
+ * Builds the `LogApi` over the plugin's `{ config, state }` core context:
231
+ * the leveled loggers (via a shared `append`), the frozen `trace()` snapshot,
232
+ * the live `expect()` chain, `addSink`, and `reset`.
233
+ */
234
+ /**
235
+ * Append a new entry to the trace and fan it out to every sink in order.
236
+ *
237
+ * @param state - The mutable log state to append to.
238
+ * @param level - Severity level for the entry.
239
+ * @param event - Event identifier.
240
+ * @param data - Optional structured payload.
241
+ * @example
242
+ * ```ts
243
+ * append(state, "info", "content:ready", { count: 12 });
244
+ * ```
245
+ */
246
+ function append(state, level, event, data) {
247
+ const entry = {
248
+ level,
249
+ event,
250
+ data,
251
+ ts: Date.now()
252
+ };
253
+ state.entries.push(entry);
254
+ for (const sink of state.sinks) sink.write(entry);
255
+ }
256
+ /**
257
+ * Tests whether a value is a non-null, non-array plain object.
258
+ *
259
+ * @param value - The value to test.
260
+ * @returns `true` when `value` is a non-null object that is not an array.
261
+ * @example
262
+ * ```ts
263
+ * isPlainObject({ a: 1 }); // true
264
+ * isPlainObject([1]); // false
265
+ * ```
266
+ */
267
+ function isPlainObject(value) {
268
+ return typeof value === "object" && value !== null && !Array.isArray(value);
269
+ }
270
+ /**
271
+ * Merge an `Error`'s `message`/`stack` into `data` under an `error` key. The
272
+ * `error` field is always preserved; only a plain object `data` contributes its
273
+ * keys. Non-plain-object `data` (arrays and primitives) is replaced by `{}` —
274
+ * its original value is not retained — so the merge target is always a record.
275
+ *
276
+ * @param data - Original payload (any shape).
277
+ * @param error - The originating error to merge.
278
+ * @returns A new object carrying any plain-object keys plus the `error` field.
279
+ * @example
280
+ * ```ts
281
+ * mergeError({ target: "cf" }, new Error("boom"));
282
+ * // { target: "cf", error: { message: "boom", stack: "..." } }
283
+ * ```
284
+ */
285
+ function mergeError(data, error) {
286
+ return {
287
+ ...isPlainObject(data) ? data : {},
288
+ error: {
289
+ message: error.message,
290
+ stack: error.stack
291
+ }
292
+ };
293
+ }
294
+ /**
295
+ * Create the log plugin API surface injected as `ctx.log` / `app.log`.
296
+ *
297
+ * @param ctx - Core plugin context (`{ config, state }`).
298
+ * @returns The {@link LogApi} bound to `ctx.state`.
299
+ * @example
300
+ * ```ts
301
+ * const log = createLogApi(ctx);
302
+ * log.info("content:ready", { articleCount: 12 });
303
+ * ```
304
+ */
305
+ function createLogApi(ctx) {
306
+ const { state } = ctx;
307
+ return {
308
+ /**
309
+ * Append an `info` entry and fan it out to every sink.
310
+ *
311
+ * @param event - Event identifier (convention: `domain:action`).
312
+ * @param data - Optional structured payload.
313
+ * @example
314
+ * ```ts
315
+ * log.info("content:ready", { count: 12 });
316
+ * ```
317
+ */
318
+ info(event, data) {
319
+ append(state, "info", event, data);
320
+ },
321
+ /**
322
+ * Append a `debug` entry and fan it out to every sink.
323
+ *
324
+ * @param event - Event identifier (convention: `domain:action`).
325
+ * @param data - Optional structured payload.
326
+ * @example
327
+ * ```ts
328
+ * log.debug("router:match", { path: "/blog/" });
329
+ * ```
330
+ */
331
+ debug(event, data) {
332
+ append(state, "debug", event, data);
333
+ },
334
+ /**
335
+ * Append a `warn` entry and fan it out to every sink.
336
+ *
337
+ * @param event - Event identifier (convention: `domain:action`).
338
+ * @param data - Optional structured payload.
339
+ * @example
340
+ * ```ts
341
+ * log.warn("build:skip", { reason: "no sitemap" });
342
+ * ```
343
+ */
344
+ warn(event, data) {
345
+ append(state, "warn", event, data);
346
+ },
347
+ /**
348
+ * Append an `error` entry. When `error` is provided, its `message`/`stack`
349
+ * are merged into `data` under an `error` key (existing keys preserved);
350
+ * otherwise `data` is recorded as-is.
351
+ *
352
+ * @param event - Event identifier (convention: `domain:action`).
353
+ * @param data - Optional structured payload.
354
+ * @param error - Optional originating Error to merge into `data`.
355
+ * @example
356
+ * ```ts
357
+ * log.error("deploy:failed", { target: "cf" }, err);
358
+ * ```
359
+ */
360
+ error(event, data, error) {
361
+ append(state, "error", event, error === void 0 ? data : mergeError(data, error));
362
+ },
363
+ /**
364
+ * Return a frozen snapshot (fresh copy) of the entries recorded so far.
365
+ *
366
+ * @returns A readonly, frozen copy of the recorded entries.
367
+ * @example
368
+ * ```ts
369
+ * const entries = log.trace();
370
+ * ```
371
+ */
372
+ trace() {
373
+ return Object.freeze([...state.entries]);
374
+ },
375
+ /**
376
+ * Return a fluent assertion chain bound to the live entries array.
377
+ *
378
+ * @returns A fresh {@link ExpectChain} reading `state.entries` live.
379
+ * @example
380
+ * ```ts
381
+ * log.expect().toHaveEvent("build:complete");
382
+ * ```
383
+ */
384
+ expect() {
385
+ return createExpectChain(state.entries);
386
+ },
387
+ /**
388
+ * Register an additional output sink at runtime.
389
+ *
390
+ * @param sink - The sink to add to the fan-out list.
391
+ * @example
392
+ * ```ts
393
+ * log.addSink({ write: (e) => stream.write(JSON.stringify(e)) });
394
+ * ```
395
+ */
396
+ addSink(sink) {
397
+ state.sinks.push(sink);
398
+ },
399
+ /**
400
+ * Clear all recorded entries while keeping registered sinks.
401
+ *
402
+ * @example
403
+ * ```ts
404
+ * log.reset();
405
+ * ```
406
+ */
407
+ reset() {
408
+ state.entries.length = 0;
409
+ }
410
+ };
411
+ }
412
+ //#endregion
413
+ //#region src/plugins/log/sinks.ts
414
+ /** Severity rank for threshold comparison (higher = more severe). */
415
+ const LEVEL_RANK = {
416
+ debug: 10,
417
+ info: 20,
418
+ warn: 30,
419
+ error: 40
420
+ };
421
+ /**
422
+ * Build the console sink: routes entries by channel — `error` → `console.error`,
423
+ * `warn` → `console.warn`, and `debug`/`info` → `console.log`. The full entry
424
+ * object is forwarded so the console serializes its `event` and `data`. Entries
425
+ * below `minLevel` are dropped (the in-memory trace still records everything).
426
+ *
427
+ * @param minLevel - Lowest severity to print. Defaults to `"debug"` (print all).
428
+ * @returns A {@link LogSink} that writes to the matching `console` channel.
429
+ * @example
430
+ * ```ts
431
+ * state.sinks.push(consoleSink("info")); // suppress debug spam
432
+ * ```
433
+ */
434
+ function consoleSink(minLevel = "debug") {
435
+ const threshold = LEVEL_RANK[minLevel];
436
+ return {
437
+ /**
438
+ * Route a single entry to the console channel matching its level.
439
+ *
440
+ * @param entry - The entry to emit.
441
+ * @example
442
+ * ```ts
443
+ * sink.write({ level: "warn", event: "build:skip", ts: Date.now() });
444
+ * ```
445
+ */
446
+ write(entry) {
447
+ if (LEVEL_RANK[entry.level] < threshold) return;
448
+ if (entry.level === "error") console.error(entry);
449
+ else if (entry.level === "warn") console.warn(entry);
450
+ else console.log(entry);
451
+ } };
452
+ }
453
+ /**
454
+ * Install mode-selected default sinks at onInit. The in-memory trace is always
455
+ * on (`state.entries`); the console sink is added only in dev/production. `dev`
456
+ * prints everything (debug+); `production` prints `info`+ only, so the per-phase
457
+ * `debug` events (build:bundle, build:pages, …) don't spam a prod build. Both
458
+ * modes still record all levels in the in-memory trace.
459
+ *
460
+ * @param ctx - Core plugin context (`{ config, state }`).
461
+ * @param ctx.config - Resolved log config (`{ mode }`).
462
+ * @param ctx.state - Mutable log state (`{ entries, sinks }`).
463
+ * @example
464
+ * ```ts
465
+ * // "dev" -> [consoleSink("debug")]; "production" -> [consoleSink("info")]; "test"/"silent" -> []
466
+ * ```
467
+ */
468
+ function installDefaultSinks(ctx) {
469
+ if (ctx.config.mode === "dev") ctx.state.sinks.push(consoleSink("debug"));
470
+ else if (ctx.config.mode === "production") ctx.state.sinks.push(consoleSink("info"));
471
+ }
472
+ //#endregion
473
+ //#region src/plugins/log/state.ts
474
+ /**
475
+ * Create fresh log state: an empty append-only trace and an empty sink list.
476
+ * No module-level singletons — guarantees per-`createApp` isolation (two
477
+ * `createApp` calls never share `entries` or `sinks`).
478
+ *
479
+ * @param _ctx - Core plugin context (`{ config }`); unused at construction.
480
+ * @returns A fresh `LogState` with empty `entries` and `sinks` arrays.
481
+ * @example
482
+ * ```ts
483
+ * const state = createLogState({ config: { mode: "test" } }); // { entries: [], sinks: [] }
484
+ * ```
485
+ */
486
+ function createLogState(_ctx) {
487
+ return {
488
+ entries: [],
489
+ sinks: []
490
+ };
491
+ }
492
+ /**
493
+ * Core logging plugin — always-on in-memory trace + `expect()` event-trace DSL.
494
+ * API injected as `ctx.log` on every regular plugin and surfaced as `app.log`.
495
+ * No depends / events / hooks (core plugin per spec/03 §5).
496
+ *
497
+ * @see README.md
498
+ */
499
+ const logPlugin = (0, _moku_labs_core.createCorePlugin)("log", {
500
+ config: { mode: "production" },
501
+ createState: createLogState,
502
+ api: createLogApi,
503
+ onInit: installDefaultSinks
504
+ });
505
+ //#endregion
506
+ //#region src/plugins/env/api.ts
507
+ /** Error prefix for all env API failures. */
508
+ const ERROR_PREFIX$1 = "[web]";
509
+ /**
510
+ * Creates the env plugin API surface mounted at `ctx.env`. Closes over
511
+ * `ctx.state` ({@link EnvState}) and reads the frozen `resolved` / `publicMap`
512
+ * maps; closures never return a raw `ctx.state` reference.
513
+ *
514
+ * @param ctx - Core plugin context carrying the frozen env state.
515
+ * @param ctx.state - The resolved + public {@link EnvState} maps.
516
+ * @returns The {@link EnvApi} accessor surface mounted at `ctx.env`.
517
+ * @example
518
+ * ```ts
519
+ * const api = createEnvApi(ctx);
520
+ * api.get("PUBLIC_API_URL");
521
+ * ```
522
+ */
523
+ function createEnvApi(ctx) {
524
+ const { resolved, publicMap } = ctx.state;
525
+ return {
526
+ /**
527
+ * Reads a resolved variable.
528
+ *
529
+ * @param key - Variable name.
530
+ * @returns The value, or `undefined` if not present.
531
+ * @example
532
+ * ```ts
533
+ * api.get("PUBLIC_API_URL");
534
+ * ```
535
+ */
536
+ get(key) {
537
+ return resolved.get(key);
538
+ },
539
+ /**
540
+ * Reads a variable that must exist.
541
+ *
542
+ * @param key - Variable name.
543
+ * @returns The value.
544
+ * @throws {Error} If the variable is undefined.
545
+ * @example
546
+ * ```ts
547
+ * api.require("DEPLOY_TOKEN");
548
+ * ```
549
+ */
550
+ require(key) {
551
+ const value = resolved.get(key);
552
+ if (value === void 0) throw new Error(`${ERROR_PREFIX$1} env: required variable "${key}" is not defined.`);
553
+ return value;
554
+ },
555
+ /**
556
+ * Tests presence of a resolved variable.
557
+ *
558
+ * @param key - Variable name.
559
+ * @returns `true` if a value is present.
560
+ * @example
561
+ * ```ts
562
+ * api.has("PUBLIC_API_URL");
563
+ * ```
564
+ */
565
+ has(key) {
566
+ return resolved.has(key);
567
+ },
568
+ /**
569
+ * Returns all public variables as a frozen plain object — a fresh copy,
570
+ * never the raw state map.
571
+ *
572
+ * @returns A frozen `Record` of public variable names to values.
573
+ * @example
574
+ * ```ts
575
+ * const payload = { ...api.getPublic() };
576
+ * ```
577
+ */
578
+ getPublic() {
579
+ return Object.freeze(Object.fromEntries(publicMap));
580
+ },
581
+ /**
582
+ * Returns the already-frozen map of public variables.
583
+ *
584
+ * @returns The frozen public map.
585
+ * @example
586
+ * ```ts
587
+ * [...api.getPublicMap()];
588
+ * ```
589
+ */
590
+ getPublicMap() {
591
+ return publicMap;
592
+ }
593
+ };
594
+ }
595
+ //#endregion
596
+ //#region src/plugins/env/state.ts
597
+ /**
598
+ * Creates initial env plugin state: two empty, mutable maps that are populated
599
+ * and frozen by `validateSchema` (the `onInit`) at `createApp` time.
600
+ *
601
+ * @returns A fresh `EnvState` with empty `resolved` and `publicMap` maps.
602
+ * @example
603
+ * ```ts
604
+ * const state = createEnvState();
605
+ * state.resolved.size; // 0
606
+ * ```
607
+ */
608
+ function createEnvState() {
609
+ return {
610
+ resolved: /* @__PURE__ */ new Map(),
611
+ publicMap: /* @__PURE__ */ new Map()
612
+ };
613
+ }
614
+ //#endregion
615
+ //#region src/plugins/env/validate.ts
616
+ /** Error message thrown by every frozen-map mutator. */
617
+ const FROZEN_MESSAGE = "env: map is frozen and cannot be mutated";
618
+ /** Error prefix for all resolution-pipeline failures. */
619
+ const ERROR_PREFIX = "[web]";
620
+ /** The `Map` mutators redefined as throwers when a map is frozen. */
621
+ const FROZEN_METHODS = [
622
+ "set",
623
+ "clear",
624
+ "delete"
625
+ ];
626
+ /**
627
+ * Throws the canonical frozen-map error; installed as a map's `set`/`clear`/`delete`.
628
+ *
629
+ * @throws {TypeError} Always, signalling the map is frozen.
630
+ * @example
631
+ * ```ts
632
+ * frozenThrower(); // throws TypeError
633
+ * ```
634
+ */
635
+ function frozenThrower() {
636
+ throw new TypeError(FROZEN_MESSAGE);
637
+ }
638
+ /**
639
+ * Coerces a raw provider value to its effective presence: an empty string counts
640
+ * as "absent" so a `KEY=""` falls through to later providers.
641
+ *
642
+ * @param raw - The raw value a provider supplied for a key (possibly `undefined`).
643
+ * @returns The value, or `undefined` when it is missing or an empty string.
644
+ * @example
645
+ * ```ts
646
+ * coerceEmpty(""); // => undefined
647
+ * coerceEmpty("3000"); // => "3000"
648
+ * ```
649
+ */
650
+ function coerceEmpty(raw) {
651
+ return raw === "" ? void 0 : raw;
652
+ }
653
+ /**
654
+ * Merges providers in array order, coercing empty strings to `undefined` before
655
+ * precedence so a `KEY=""` falls through to later providers. First non-empty
656
+ * value wins.
657
+ *
658
+ * @param config - The resolved env config carrying the ordered providers.
659
+ * @returns A flat record of the first defined value found per key.
660
+ * @example
661
+ * ```ts
662
+ * mergeProviders({ providers: [a, b], schema: {}, publicPrefix: "PUBLIC_" });
663
+ * ```
664
+ */
665
+ function mergeProviders(config) {
666
+ const merged = {};
667
+ for (const provider of config.providers) for (const [key, raw] of Object.entries(provider.load())) {
668
+ const value = coerceEmpty(raw);
669
+ if (value !== void 0 && merged[key] === void 0) merged[key] = value;
670
+ }
671
+ return merged;
672
+ }
673
+ /**
674
+ * Bidirectionally enforces the `PUBLIC_` naming convention against each schema
675
+ * entry's `public` flag. Throws on either violation direction.
676
+ *
677
+ * @param config - The resolved env config carrying `schema` + `publicPrefix`.
678
+ * @throws {Error} If a public var lacks the prefix, or a prefixed var is not public.
679
+ * @example
680
+ * ```ts
681
+ * crossCheckPublicPrefix(config); // throws if PUBLIC_X is not public:true
682
+ * ```
683
+ */
684
+ function crossCheckPublicPrefix(config) {
685
+ const { schema, publicPrefix } = config;
686
+ for (const [key, spec] of Object.entries(schema)) {
687
+ const hasPrefix = key.startsWith(publicPrefix);
688
+ if (spec.public === true && !hasPrefix) throw new Error(`${ERROR_PREFIX} env: "${key}" is marked public but does not start with "${publicPrefix}".`);
689
+ if (hasPrefix && spec.public !== true) throw new Error(`${ERROR_PREFIX} env: "${key}" starts with "${publicPrefix}" but is not marked public:true.`);
690
+ }
691
+ }
692
+ /**
693
+ * Seals a map so `set`, `clear`, and `delete` throw, then `Object.freeze`s it
694
+ * for defense in depth. Closes the `Object.freeze`-on-`Map` mutability hole by
695
+ * redefining the mutators as non-writable, non-configurable throwers.
696
+ *
697
+ * @param map - The map to freeze in place.
698
+ * @example
699
+ * ```ts
700
+ * freezeMap(state.resolved); // resolved.set(...) now throws
701
+ * ```
702
+ */
703
+ function freezeMap(map) {
704
+ for (const method of FROZEN_METHODS) Object.defineProperty(map, method, {
705
+ value: frozenThrower,
706
+ writable: false,
707
+ configurable: false,
708
+ enumerable: false
709
+ });
710
+ Object.freeze(map);
711
+ }
712
+ /**
713
+ * Populates `state.publicMap` with the schema-driven public subset: every
714
+ * `public:true` schema key that resolved to a defined value. This map is the only
715
+ * sanctioned input to a browser-facing `define`, so it stays schema-scoped (never
716
+ * includes non-schema provider keys).
717
+ *
718
+ * @param schema - The per-variable schema from {@link EnvConfig}.
719
+ * @param merged - The merged provider values keyed by variable name.
720
+ * @param publicMap - The mutable public map to fill in place.
721
+ * @example
722
+ * ```ts
723
+ * populatePublicMap(config.schema, merged, state.publicMap);
724
+ * ```
725
+ */
726
+ function populatePublicMap(schema, merged, publicMap) {
727
+ for (const [key, spec] of Object.entries(schema)) {
728
+ const value = merged[key];
729
+ if (spec.public === true && value !== void 0) publicMap.set(key, value);
730
+ }
731
+ }
732
+ /**
733
+ * Populates `state.resolved` with EVERY merged key that carries a defined value
734
+ * (spec/02 Lifecycle §5), including non-schema provider keys so
735
+ * `ctx.env.require()` works for dynamic keys.
736
+ *
737
+ * @param merged - The merged provider values keyed by variable name.
738
+ * @param resolved - The mutable resolved map to fill in place.
739
+ * @example
740
+ * ```ts
741
+ * populateResolved(merged, state.resolved);
742
+ * ```
743
+ */
744
+ function populateResolved(merged, resolved) {
745
+ for (const [key, value] of Object.entries(merged)) resolved.set(key, value);
746
+ }
747
+ /**
748
+ * Resolves, validates, and freezes the environment table at `onInit`.
749
+ *
750
+ * Pipeline order: merge providers (with empty-string → undefined coercion) →
751
+ * `PUBLIC_` bidirectional cross-check → apply defaults → assert required →
752
+ * populate `state.resolved` / `state.publicMap` → freeze both via
753
+ * {@link freezeMap}. Fail-fast: any violation throws at `createApp` time.
754
+ *
755
+ * @param ctx - Core plugin context (`{ config, state }`).
756
+ * @param ctx.config - The resolved {@link EnvConfig}.
757
+ * @param ctx.state - The mutable {@link EnvState} to populate and freeze.
758
+ * @throws {Error} On a `PUBLIC_` cross-check violation or a missing required variable.
759
+ * @example
760
+ * ```ts
761
+ * validateSchema(ctx); // throws on missing required / PUBLIC_ violation
762
+ * ```
763
+ */
764
+ function validateSchema(ctx) {
765
+ const { config, state } = ctx;
766
+ const { schema } = config;
767
+ const merged = mergeProviders(config);
768
+ crossCheckPublicPrefix(config);
769
+ for (const [key, spec] of Object.entries(schema)) {
770
+ if (merged[key] === void 0 && spec.default !== void 0) merged[key] = spec.default;
771
+ if (merged[key] === void 0 && spec.required === true) throw new Error(`${ERROR_PREFIX} env: required variable "${key}" is not defined by any provider or default.`);
772
+ }
773
+ populatePublicMap(schema, merged, state.publicMap);
774
+ populateResolved(merged, state.resolved);
775
+ freezeMap(state.resolved);
776
+ freezeMap(state.publicMap);
777
+ }
778
+ //#endregion
779
+ //#region src/plugins/env/providers.browser.ts
780
+ /** Default `globalThis` property holding a runtime-injected public-env snapshot. */
781
+ const DEFAULT_GLOBAL_KEY = "__ENV__";
782
+ /**
783
+ * A browser-safe {@link EnvProvider} that reads `import.meta.env` and an optional
784
+ * `globalThis[globalKey]` snapshot, merging them with the runtime global winning.
785
+ * Contains zero `node:*` imports, so it is safe to include in the client bundle.
786
+ * Never throws on missing sources — each absent source resolves to `{}`.
787
+ *
788
+ * @param options - Optional settings.
789
+ * @param options.globalKey - `globalThis` key to read a public-env snapshot from. Defaults to `"__ENV__"`.
790
+ * @returns An {@link EnvProvider} named `browser-env`.
791
+ * @example
792
+ * ```ts
793
+ * const provider = browserEnv();
794
+ * provider.load(); // { PUBLIC_API_URL: "/api", ... }
795
+ * ```
796
+ */
797
+ function browserEnv(options) {
798
+ const globalKey = options?.globalKey ?? DEFAULT_GLOBAL_KEY;
799
+ return {
800
+ name: "browser-env",
801
+ /**
802
+ * Merges `import.meta.env` with `globalThis[globalKey]`, the runtime global
803
+ * winning. Each absent source resolves to `{}`; never throws.
804
+ *
805
+ * @returns The merged environment record.
806
+ * @example
807
+ * ```ts
808
+ * browserEnv().load();
809
+ * ```
810
+ */
811
+ load() {
812
+ const importEnv = {}.env ?? {};
813
+ const globalObject = globalThis[globalKey] ?? {};
814
+ return {
815
+ ...importEnv,
816
+ ...globalObject
817
+ };
818
+ }
819
+ };
820
+ }
821
+ /**
822
+ * Core plugin that resolves, validates, and freezes the environment at `onInit`,
823
+ * exposing a read-only accessor at `ctx.env`. No `onStart`/`onStop` — holds no resource.
824
+ *
825
+ * @example
826
+ * ```ts
827
+ * createApp({ pluginConfigs: { env: { schema: { PUBLIC_API_URL: { public: true } } } } });
828
+ * ```
829
+ */
830
+ const envPlugin = (0, _moku_labs_core.createCorePlugin)("env", {
831
+ config: {
832
+ schema: {},
833
+ providers: [],
834
+ publicPrefix: "PUBLIC_"
835
+ },
836
+ createState: createEnvState,
837
+ api: createEnvApi,
838
+ onInit: validateSchema
839
+ });
840
+ //#endregion
841
+ //#region src/plugins/env/providers.ts
842
+ /**
843
+ * @file env plugin — built-in providers: dotenv, processEnv, cloudflareBindings.
844
+ */
845
+ /** Default dotenv file path: optional local overrides. */
846
+ const DEFAULT_DOTENV_PATH = ".env.local";
847
+ /** Property on `globalThis` that the consumer sets per Cloudflare request. */
848
+ const CLOUDFLARE_GLOBAL = "__CLOUDFLARE_ENV__";
849
+ /** `String.indexOf` sentinel meaning "no `=` separator on this line". */
850
+ const NO_SEPARATOR = -1;
851
+ /**
852
+ * Strips a single matching pair of surrounding double or single quotes from a
853
+ * value. Leaves unquoted values (and trailing inline comments) untouched.
854
+ *
855
+ * @param value - The already-trimmed raw value.
856
+ * @returns The value with one outer quote pair removed, if present.
857
+ * @example
858
+ * ```ts
859
+ * stripQuotes('"a"'); // "a"
860
+ * stripQuotes("plain # c"); // "plain # c"
861
+ * ```
862
+ */
863
+ function stripQuotes(value) {
864
+ if (value.length < 2) return value;
865
+ const first = value[0];
866
+ const last = value.at(-1);
867
+ if ((first === "\"" || first === "'") && first === last) return value.slice(1, -1);
868
+ return value;
869
+ }
870
+ /**
871
+ * Reports whether a trimmed line carries no assignment — a blank line or a
872
+ * full-line `#` comment — and should be skipped by the parser.
873
+ *
874
+ * @param trimmed - A whitespace-trimmed line from the dotenv text.
875
+ * @returns `true` when the line is empty or a comment.
876
+ * @example
877
+ * ```ts
878
+ * isIgnoredLine(""); // true
879
+ * isIgnoredLine("# note"); // true
880
+ * isIgnoredLine("A=1"); // false
881
+ * ```
882
+ */
883
+ function isIgnoredLine(trimmed) {
884
+ return trimmed === "" || trimmed.startsWith("#");
885
+ }
886
+ /**
887
+ * Parses `.env`-style text into a flat record. Handles CRLF/LF, blank lines,
888
+ * full-line `#` comments, first-`=` splitting, key/value trimming, and a single
889
+ * outer quote pair. Does not strip trailing inline comments on unquoted values.
890
+ *
891
+ * @param text - The raw file contents.
892
+ * @returns A flat record of parsed key/value pairs.
893
+ * @example
894
+ * ```ts
895
+ * parseDotenv('A=1\nB="two"'); // { A: "1", B: "two" }
896
+ * ```
897
+ */
898
+ function parseDotenv(text) {
899
+ const out = {};
900
+ for (const line of text.split(/\r?\n/)) {
901
+ const trimmed = line.trim();
902
+ if (isIgnoredLine(trimmed)) continue;
903
+ const eq = trimmed.indexOf("=");
904
+ if (eq === NO_SEPARATOR) continue;
905
+ const key = trimmed.slice(0, eq).trim();
906
+ out[key] = stripQuotes(trimmed.slice(eq + 1).trim());
907
+ }
908
+ return out;
909
+ }
910
+ /**
911
+ * A zero-dependency `.env`-style provider that re-reads and re-parses the file
912
+ * from disk on every `load()`. Missing file resolves to `{}` (optional
913
+ * overrides). Strips a single outer quote pair; does not strip trailing inline
914
+ * comments on unquoted values.
915
+ *
916
+ * @param path - Path to the dotenv file. Defaults to `.env.local`.
917
+ * @returns An {@link EnvProvider} named `dotenv:<path>` that reads fresh per call.
918
+ * @example
919
+ * ```ts
920
+ * const provider = dotenv(".env.local");
921
+ * provider.load(); // { PUBLIC_API_URL: "/api", ... }
922
+ * ```
923
+ */
924
+ function dotenv(path = DEFAULT_DOTENV_PATH) {
925
+ return {
926
+ name: `dotenv:${path}`,
927
+ /**
928
+ * Reads and parses the dotenv file fresh from disk; `{}` if it is missing.
929
+ *
930
+ * @returns The parsed environment record, or `{}` when the file is absent.
931
+ * @example
932
+ * ```ts
933
+ * dotenv(".env.local").load();
934
+ * ```
935
+ */
936
+ load() {
937
+ if (!(0, node_fs.existsSync)(path)) return {};
938
+ return parseDotenv((0, node_fs.readFileSync)(path, "utf8"));
939
+ }
940
+ };
941
+ }
942
+ /**
943
+ * A provider that returns a shallow copy of `process.env` at `load()` time.
944
+ *
945
+ * @returns An {@link EnvProvider} named `process-env`.
946
+ * @example
947
+ * ```ts
948
+ * const provider = processEnv();
949
+ * provider.load().HOME; // current process value
950
+ * ```
951
+ */
952
+ function processEnv() {
953
+ return {
954
+ name: "process-env",
955
+ /**
956
+ * Returns a shallow copy of `process.env` at call time.
957
+ *
958
+ * @returns A fresh shallow copy of `process.env`.
959
+ * @example
960
+ * ```ts
961
+ * processEnv().load();
962
+ * ```
963
+ */
964
+ load() {
965
+ return { ...process.env };
966
+ }
967
+ };
968
+ }
969
+ /**
970
+ * A provider that reads live, per-request Cloudflare bindings from
971
+ * `globalThis.__CLOUDFLARE_ENV__` at `load()` time (`?? {}` when absent). Never
972
+ * caches the binding object; the consumer owns the global's request lifecycle.
973
+ *
974
+ * @returns An {@link EnvProvider} named `cloudflare`.
975
+ * @example
976
+ * ```ts
977
+ * globalThis.__CLOUDFLARE_ENV__ = env; // set by the request handler
978
+ * const provider = cloudflareBindings();
979
+ * provider.load(); // reads the current request's bindings
980
+ * ```
981
+ */
982
+ function cloudflareBindings() {
983
+ return {
984
+ name: "cloudflare",
985
+ /**
986
+ * Reads `globalThis.__CLOUDFLARE_ENV__` fresh, never caching the bindings.
987
+ *
988
+ * @returns The current Cloudflare bindings, or `{}` when the global is unset.
989
+ * @example
990
+ * ```ts
991
+ * cloudflareBindings().load();
992
+ * ```
993
+ */
994
+ load() {
995
+ return globalThis[CLOUDFLARE_GLOBAL] ?? {};
996
+ }
997
+ };
998
+ }
999
+ //#endregion
1000
+ //#region src/plugins/log/types.ts
1001
+ var types_exports$1 = /* @__PURE__ */ __exportAll({});
1002
+ //#endregion
1003
+ //#region src/plugins/env/types.ts
1004
+ var types_exports = /* @__PURE__ */ __exportAll({});
1005
+ //#endregion
1006
+ Object.defineProperty(exports, "Env", {
1007
+ enumerable: true,
1008
+ get: function() {
1009
+ return types_exports;
1010
+ }
1011
+ });
1012
+ Object.defineProperty(exports, "Log", {
1013
+ enumerable: true,
1014
+ get: function() {
1015
+ return types_exports$1;
1016
+ }
1017
+ });
1018
+ exports.browserEnv = browserEnv;
1019
+ exports.cloudflareBindings = cloudflareBindings;
1020
+ exports.dotenv = dotenv;
1021
+ exports.envPlugin = envPlugin;
1022
+ exports.logPlugin = logPlugin;
1023
+ exports.processEnv = processEnv;