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