@moku-labs/web 1.12.2 → 1.12.4

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 CHANGED
@@ -1,5 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_convention = require("./convention-BpDfzX7e.cjs");
3
+ let _moku_labs_common = require("@moku-labs/common");
3
4
  let _moku_labs_core = require("@moku-labs/core");
4
5
  let node_fs = require("node:fs");
5
6
  let node_crypto = require("node:crypto");
@@ -41,831 +42,6 @@ let hast_util_sanitize = require("hast-util-sanitize");
41
42
  let reading_time = require("reading-time");
42
43
  reading_time = require_convention.__toESM(reading_time, 1);
43
44
  let node_process = require("node:process");
44
- //#region src/plugins/env/api.ts
45
- /** Error prefix for all env API failures. */
46
- const ERROR_PREFIX$16 = "[web]";
47
- /**
48
- * Creates the env plugin API surface mounted at `ctx.env`. Closes over
49
- * `ctx.state` ({@link EnvState}) and reads the frozen `resolved` / `publicMap`
50
- * maps; closures never return a raw `ctx.state` reference.
51
- *
52
- * @param ctx - Core plugin context carrying the frozen env state.
53
- * @param ctx.state - The resolved + public {@link EnvState} maps.
54
- * @returns The {@link EnvApi} accessor surface mounted at `ctx.env`.
55
- * @example
56
- * ```ts
57
- * const api = createEnvApi(ctx);
58
- * api.get("PUBLIC_API_URL");
59
- * ```
60
- */
61
- function createEnvApi(ctx) {
62
- const { resolved, publicMap } = ctx.state;
63
- return {
64
- /**
65
- * Reads a resolved variable.
66
- *
67
- * @param key - Variable name.
68
- * @returns The value, or `undefined` if not present.
69
- * @example
70
- * ```ts
71
- * api.get("PUBLIC_API_URL");
72
- * ```
73
- */
74
- get(key) {
75
- return resolved.get(key);
76
- },
77
- /**
78
- * Reads a variable that must exist.
79
- *
80
- * @param key - Variable name.
81
- * @returns The value.
82
- * @throws {Error} If the variable is undefined.
83
- * @example
84
- * ```ts
85
- * api.require("DEPLOY_TOKEN");
86
- * ```
87
- */
88
- require(key) {
89
- const value = resolved.get(key);
90
- if (value === void 0) throw new Error(`${ERROR_PREFIX$16} env: required variable "${key}" is not defined.`);
91
- return value;
92
- },
93
- /**
94
- * Tests presence of a resolved variable.
95
- *
96
- * @param key - Variable name.
97
- * @returns `true` if a value is present.
98
- * @example
99
- * ```ts
100
- * api.has("PUBLIC_API_URL");
101
- * ```
102
- */
103
- has(key) {
104
- return resolved.has(key);
105
- },
106
- /**
107
- * Returns all public variables as a frozen plain object — a fresh copy,
108
- * never the raw state map.
109
- *
110
- * @returns A frozen `Record` of public variable names to values.
111
- * @example
112
- * ```ts
113
- * const payload = { ...api.getPublic() };
114
- * ```
115
- */
116
- getPublic() {
117
- return Object.freeze(Object.fromEntries(publicMap));
118
- },
119
- /**
120
- * Returns the already-frozen map of public variables.
121
- *
122
- * @returns The frozen public map.
123
- * @example
124
- * ```ts
125
- * [...api.getPublicMap()];
126
- * ```
127
- */
128
- getPublicMap() {
129
- return publicMap;
130
- }
131
- };
132
- }
133
- //#endregion
134
- //#region src/plugins/env/state.ts
135
- /**
136
- * Creates initial env plugin state: two empty, mutable maps that are populated
137
- * and frozen by `validateSchema` (the `onInit`) at `createApp` time.
138
- *
139
- * @returns A fresh `EnvState` with empty `resolved` and `publicMap` maps.
140
- * @example
141
- * ```ts
142
- * const state = createEnvState();
143
- * state.resolved.size; // 0
144
- * ```
145
- */
146
- function createEnvState() {
147
- return {
148
- resolved: /* @__PURE__ */ new Map(),
149
- publicMap: /* @__PURE__ */ new Map()
150
- };
151
- }
152
- //#endregion
153
- //#region src/plugins/env/validate.ts
154
- /** Error message thrown by every frozen-map mutator. */
155
- const FROZEN_MESSAGE = "env: map is frozen and cannot be mutated";
156
- /** Error prefix for all resolution-pipeline failures. */
157
- const ERROR_PREFIX$15 = "[web]";
158
- /** The `Map` mutators redefined as throwers when a map is frozen. */
159
- const FROZEN_METHODS = [
160
- "set",
161
- "clear",
162
- "delete"
163
- ];
164
- /**
165
- * Throws the canonical frozen-map error; installed as a map's `set`/`clear`/`delete`.
166
- *
167
- * @throws {TypeError} Always, signalling the map is frozen.
168
- * @example
169
- * ```ts
170
- * frozenThrower(); // throws TypeError
171
- * ```
172
- */
173
- function frozenThrower() {
174
- throw new TypeError(FROZEN_MESSAGE);
175
- }
176
- /**
177
- * Coerces a raw provider value to its effective presence: an empty string counts
178
- * as "absent" so a `KEY=""` falls through to later providers.
179
- *
180
- * @param raw - The raw value a provider supplied for a key (possibly `undefined`).
181
- * @returns The value, or `undefined` when it is missing or an empty string.
182
- * @example
183
- * ```ts
184
- * coerceEmpty(""); // => undefined
185
- * coerceEmpty("3000"); // => "3000"
186
- * ```
187
- */
188
- function coerceEmpty(raw) {
189
- return raw === "" ? void 0 : raw;
190
- }
191
- /**
192
- * Merges providers in array order, coercing empty strings to `undefined` before
193
- * precedence so a `KEY=""` falls through to later providers. First non-empty
194
- * value wins.
195
- *
196
- * @param config - The resolved env config carrying the ordered providers.
197
- * @returns A flat record of the first defined value found per key.
198
- * @example
199
- * ```ts
200
- * mergeProviders({ providers: [a, b], schema: {}, publicPrefix: "PUBLIC_" });
201
- * ```
202
- */
203
- function mergeProviders$1(config) {
204
- const merged = {};
205
- for (const provider of config.providers) for (const [key, raw] of Object.entries(provider.load())) {
206
- const value = coerceEmpty(raw);
207
- if (value !== void 0 && merged[key] === void 0) merged[key] = value;
208
- }
209
- return merged;
210
- }
211
- /**
212
- * Bidirectionally enforces the `PUBLIC_` naming convention against each schema
213
- * entry's `public` flag. Throws on either violation direction.
214
- *
215
- * @param config - The resolved env config carrying `schema` + `publicPrefix`.
216
- * @throws {Error} If a public var lacks the prefix, or a prefixed var is not public.
217
- * @example
218
- * ```ts
219
- * crossCheckPublicPrefix(config); // throws if PUBLIC_X is not public:true
220
- * ```
221
- */
222
- function crossCheckPublicPrefix(config) {
223
- const { schema, publicPrefix } = config;
224
- for (const [key, spec] of Object.entries(schema)) {
225
- const hasPrefix = key.startsWith(publicPrefix);
226
- if (spec.public === true && !hasPrefix) throw new Error(`${ERROR_PREFIX$15} env: "${key}" is marked public but does not start with "${publicPrefix}".`);
227
- if (hasPrefix && spec.public !== true) throw new Error(`${ERROR_PREFIX$15} env: "${key}" starts with "${publicPrefix}" but is not marked public:true.`);
228
- }
229
- }
230
- /**
231
- * Seals a map so `set`, `clear`, and `delete` throw, then `Object.freeze`s it
232
- * for defense in depth. Closes the `Object.freeze`-on-`Map` mutability hole by
233
- * redefining the mutators as non-writable, non-configurable throwers.
234
- *
235
- * @param map - The map to freeze in place.
236
- * @example
237
- * ```ts
238
- * freezeMap(state.resolved); // resolved.set(...) now throws
239
- * ```
240
- */
241
- function freezeMap(map) {
242
- for (const method of FROZEN_METHODS) Object.defineProperty(map, method, {
243
- value: frozenThrower,
244
- writable: false,
245
- configurable: false,
246
- enumerable: false
247
- });
248
- Object.freeze(map);
249
- }
250
- /**
251
- * Populates `state.publicMap` with the schema-driven public subset: every
252
- * `public:true` schema key that resolved to a defined value. This map is the only
253
- * sanctioned input to a browser-facing `define`, so it stays schema-scoped (never
254
- * includes non-schema provider keys).
255
- *
256
- * @param schema - The per-variable schema from {@link EnvConfig}.
257
- * @param merged - The merged provider values keyed by variable name.
258
- * @param publicMap - The mutable public map to fill in place.
259
- * @example
260
- * ```ts
261
- * populatePublicMap(config.schema, merged, state.publicMap);
262
- * ```
263
- */
264
- function populatePublicMap(schema, merged, publicMap) {
265
- for (const [key, spec] of Object.entries(schema)) {
266
- const value = merged[key];
267
- if (spec.public === true && value !== void 0) publicMap.set(key, value);
268
- }
269
- }
270
- /**
271
- * Populates `state.resolved` with EVERY merged key that carries a defined value
272
- * (spec/02 Lifecycle §5), including non-schema provider keys so
273
- * `ctx.env.require()` works for dynamic keys.
274
- *
275
- * @param merged - The merged provider values keyed by variable name.
276
- * @param resolved - The mutable resolved map to fill in place.
277
- * @example
278
- * ```ts
279
- * populateResolved(merged, state.resolved);
280
- * ```
281
- */
282
- function populateResolved(merged, resolved) {
283
- for (const [key, value] of Object.entries(merged)) resolved.set(key, value);
284
- }
285
- /**
286
- * Resolves, validates, and freezes the environment table at `onInit`.
287
- *
288
- * Pipeline order: merge providers (with empty-string → undefined coercion) →
289
- * `PUBLIC_` bidirectional cross-check → apply defaults → assert required →
290
- * populate `state.resolved` / `state.publicMap` → freeze both via
291
- * {@link freezeMap}. Fail-fast: any violation throws at `createApp` time.
292
- *
293
- * @param ctx - Core plugin context (`{ config, state }`).
294
- * @param ctx.config - The resolved {@link EnvConfig}.
295
- * @param ctx.state - The mutable {@link EnvState} to populate and freeze.
296
- * @throws {Error} On a `PUBLIC_` cross-check violation or a missing required variable.
297
- * @example
298
- * ```ts
299
- * validateSchema(ctx); // throws on missing required / PUBLIC_ violation
300
- * ```
301
- */
302
- function validateSchema(ctx) {
303
- const { config, state } = ctx;
304
- const { schema } = config;
305
- const merged = mergeProviders$1(config);
306
- crossCheckPublicPrefix(config);
307
- for (const [key, spec] of Object.entries(schema)) {
308
- if (merged[key] === void 0 && spec.default !== void 0) merged[key] = spec.default;
309
- if (merged[key] === void 0 && spec.required === true) throw new Error(`${ERROR_PREFIX$15} env: required variable "${key}" is not defined by any provider or default.`);
310
- }
311
- populatePublicMap(schema, merged, state.publicMap);
312
- populateResolved(merged, state.resolved);
313
- freezeMap(state.resolved);
314
- freezeMap(state.publicMap);
315
- }
316
- //#endregion
317
- //#region src/plugins/env/providers.browser.ts
318
- /** Default `globalThis` property holding a runtime-injected public-env snapshot. */
319
- const DEFAULT_GLOBAL_KEY = "__ENV__";
320
- /**
321
- * A browser-safe {@link EnvProvider} that reads `import.meta.env` and an optional
322
- * `globalThis[globalKey]` snapshot, merging them with the runtime global winning.
323
- * Contains zero `node:*` imports, so it is safe to include in the client bundle.
324
- * Never throws on missing sources — each absent source resolves to `{}`.
325
- *
326
- * @param options - Optional settings.
327
- * @param options.globalKey - `globalThis` key to read a public-env snapshot from. Defaults to `"__ENV__"`.
328
- * @returns An {@link EnvProvider} named `browser-env`.
329
- * @example
330
- * ```ts
331
- * const provider = browserEnv();
332
- * provider.load(); // { PUBLIC_API_URL: "/api", ... }
333
- * ```
334
- */
335
- function browserEnv(options) {
336
- const globalKey = options?.globalKey ?? DEFAULT_GLOBAL_KEY;
337
- return {
338
- name: "browser-env",
339
- /**
340
- * Merges `import.meta.env` with `globalThis[globalKey]`, the runtime global
341
- * winning. Each absent source resolves to `{}`; never throws.
342
- *
343
- * @returns The merged environment record.
344
- * @example
345
- * ```ts
346
- * browserEnv().load();
347
- * ```
348
- */
349
- load() {
350
- const importEnv = {}.env ?? {};
351
- const globalObject = globalThis[globalKey] ?? {};
352
- return {
353
- ...importEnv,
354
- ...globalObject
355
- };
356
- }
357
- };
358
- }
359
- /**
360
- * Core plugin that resolves, validates, and freezes the environment at `onInit`,
361
- * exposing a read-only accessor at `ctx.env`. No `onStart`/`onStop` — holds no resource.
362
- *
363
- * @example
364
- * ```ts
365
- * createApp({ pluginConfigs: { env: { schema: { PUBLIC_API_URL: { public: true } } } } });
366
- * ```
367
- */
368
- const envPlugin = (0, _moku_labs_core.createCorePlugin)("env", {
369
- config: {
370
- schema: {},
371
- providers: [],
372
- publicPrefix: "PUBLIC_"
373
- },
374
- createState: createEnvState,
375
- api: createEnvApi,
376
- onInit: validateSchema
377
- });
378
- //#endregion
379
- //#region src/plugins/log/expect.ts
380
- /**
381
- * Named error thrown by `expect()` assertions when a trace condition fails.
382
- *
383
- * @example
384
- * ```ts
385
- * throw new LogExpectAssertionError("missing event build:complete");
386
- * ```
387
- */
388
- var LogExpectAssertionError = class extends Error {
389
- /**
390
- * Construct a new assertion error with a descriptive failure message.
391
- *
392
- * @param message - Descriptive failure message (event name, partial, index).
393
- * @example
394
- * ```ts
395
- * throw new LogExpectAssertionError("missing event build:complete");
396
- * ```
397
- */
398
- constructor(message) {
399
- super(message);
400
- this.name = "LogExpectAssertionError";
401
- }
402
- };
403
- /**
404
- * Tests whether a value is a non-null, non-array plain object.
405
- *
406
- * @param value - The value to test.
407
- * @returns `true` when `value` is a non-null object that is not an array.
408
- * @example
409
- * ```ts
410
- * isPlainObject({ a: 1 }); // true
411
- * isPlainObject([1]); // false
412
- * ```
413
- */
414
- function isPlainObject$1(value) {
415
- return typeof value === "object" && value !== null && !Array.isArray(value);
416
- }
417
- /**
418
- * Tests whether `actual` is an array that recursively matches every element of
419
- * the `partial` array (element-wise, with equal length).
420
- *
421
- * @param actual - The value to test against (must be an array of equal length).
422
- * @param partial - The expected partial array shape.
423
- * @returns `true` when `actual` is an equal-length array matching `partial` element-wise.
424
- * @example
425
- * ```ts
426
- * matchesPartialArray([1, 2], [1, 2]); // true
427
- * matchesPartialArray([1], [1, 2]); // false (length mismatch)
428
- * ```
429
- */
430
- function matchesPartialArray(actual, partial) {
431
- if (!Array.isArray(actual) || actual.length !== partial.length) return false;
432
- return partial.every((value, index) => matchesPartial(actual[index], value));
433
- }
434
- /**
435
- * Tests whether `actual` is a plain object in which every `partial` key
436
- * recursively matches (extra `actual` keys are ignored).
437
- *
438
- * @param actual - The value to test against (must be a plain object).
439
- * @param partial - The expected partial object shape.
440
- * @returns `true` when every `partial` key exists in `actual` and matches recursively.
441
- * @example
442
- * ```ts
443
- * matchesPartialObject({ a: 1, b: 2 }, { a: 1 }); // true
444
- * matchesPartialObject({ a: 1 }, { b: 1 }); // false (missing key)
445
- * ```
446
- */
447
- function matchesPartialObject(actual, partial) {
448
- if (!isPlainObject$1(actual)) return false;
449
- return Object.keys(partial).every((key) => key in actual && matchesPartial(actual[key], partial[key]));
450
- }
451
- /**
452
- * Subset-equality matcher: is `partial` a recursive subset of `actual`?
453
- *
454
- * Fast path via `Object.is` (covers identical primitives/references and
455
- * `null`/`NaN`); primitives compare with `Object.is`; arrays match element-wise
456
- * with equal length; plain objects require every `partial` key to recursively
457
- * match (extra `actual` keys ignored).
458
- *
459
- * @param actual - The value to test against (typically `entry.data`).
460
- * @param partial - The expected partial shape.
461
- * @returns `true` when `partial` is a recursive subset of `actual`.
462
- * @example
463
- * ```ts
464
- * matchesPartial({ a: 1, b: 2 }, { a: 1 }); // true
465
- * matchesPartial([1, 2], [1]); // false (length mismatch)
466
- * ```
467
- */
468
- function matchesPartial(actual, partial) {
469
- if (Object.is(actual, partial)) return true;
470
- if (Array.isArray(partial)) return matchesPartialArray(actual, partial);
471
- if (isPlainObject$1(partial)) return matchesPartialObject(actual, partial);
472
- return false;
473
- }
474
- /**
475
- * Tests whether an entry matches `event` and (when provided) `partial`.
476
- *
477
- * @param entry - The candidate trace entry.
478
- * @param event - Required event name.
479
- * @param partial - Optional partial data shape (subset-matched against `entry.data`).
480
- * @returns `true` when the entry matches the event and optional partial.
481
- * @example
482
- * ```ts
483
- * entryMatches({ level: "info", event: "a", data: { x: 1 }, ts: 0 }, "a", { x: 1 }); // true
484
- * ```
485
- */
486
- function entryMatches(entry, event, partial) {
487
- if (entry.event !== event) return false;
488
- return partial === void 0 ? true : matchesPartial(entry.data, partial);
489
- }
490
- /**
491
- * Render a `partial` for an error message, prefixed with a space when present.
492
- *
493
- * @param partial - Optional partial data shape.
494
- * @returns A ` matching <json>` suffix, or an empty string when absent.
495
- * @example
496
- * ```ts
497
- * describePartial({ ok: true }); // ' matching {"ok":true}'
498
- * ```
499
- */
500
- function describePartial(partial) {
501
- return partial === void 0 ? "" : ` matching ${JSON.stringify(partial)}`;
502
- }
503
- /**
504
- * Find the first entry with `event` at or after `startIndex`, scanning forward.
505
- *
506
- * @param entries - The trace array to scan.
507
- * @param event - Event name to find.
508
- * @param startIndex - Index to begin scanning from (inclusive).
509
- * @returns The index of the first match, or `-1` when none exists from `startIndex` on.
510
- * @example
511
- * ```ts
512
- * findEventAtOrAfter([{ event: "a" }, { event: "b" }] as LogEntry[], "b", 0); // 1
513
- * ```
514
- */
515
- function findEventAtOrAfter(entries, event, startIndex) {
516
- for (let index = startIndex; index < entries.length; index++) if (entries[index]?.event === event) return index;
517
- return -1;
518
- }
519
- /**
520
- * Create a fluent assertion chain bound to the live `entries` array. Each method
521
- * reads `entries` at call time, so assertions reflect later logging.
522
- *
523
- * @param entries - The live trace array (read on each assertion call).
524
- * @returns A fresh {@link ExpectChain} backed by `entries`.
525
- * @example
526
- * ```ts
527
- * createExpectChain(state.entries).toHaveEvent("build:complete");
528
- * ```
529
- */
530
- function createExpectChain(entries) {
531
- const chain = {
532
- /**
533
- * Assert at least one entry has `event`, optionally matching `partial`.
534
- *
535
- * @param event - Event name to find.
536
- * @param partial - Optional partial data shape (subset-matched).
537
- * @returns The same chain for chaining.
538
- * @throws {LogExpectAssertionError} When no matching entry exists.
539
- * @example
540
- * ```ts
541
- * chain.toHaveEvent("build:phase", { status: "start" });
542
- * ```
543
- */
544
- toHaveEvent(event, partial) {
545
- if (!entries.some((entry) => entryMatches(entry, event, partial))) throw new LogExpectAssertionError(`Expected trace to contain event "${event}"${describePartial(partial)}, but none was found.`);
546
- return chain;
547
- },
548
- /**
549
- * Assert all of `events` appear in the trace in the given relative order.
550
- *
551
- * @param events - Ordered list of event names (gaps allowed).
552
- * @returns The same chain for chaining.
553
- * @throws {LogExpectAssertionError} When the ordering cannot be satisfied.
554
- * @example
555
- * ```ts
556
- * chain.toHaveEventInOrder(["build:phase", "build:complete"]);
557
- * ```
558
- */
559
- toHaveEventInOrder(events) {
560
- let cursor = 0;
561
- for (const [position, event] of events.entries()) {
562
- const matchIndex = findEventAtOrAfter(entries, event, cursor);
563
- 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}.`);
564
- cursor = matchIndex + 1;
565
- }
566
- return chain;
567
- },
568
- /**
569
- * Assert NO entry has `event` (optionally narrowed by `partial`).
570
- *
571
- * @param event - Event name that must be absent.
572
- * @param partial - Optional partial data shape; only matching entries violate.
573
- * @returns The same chain for chaining.
574
- * @throws {LogExpectAssertionError} When a matching entry exists.
575
- * @example
576
- * ```ts
577
- * chain.toNotHaveEvent("deploy:failed");
578
- * ```
579
- */
580
- toNotHaveEvent(event, partial) {
581
- const offending = entries.findIndex((entry) => entryMatches(entry, event, partial));
582
- if (offending !== -1) throw new LogExpectAssertionError(`Expected trace to NOT contain event "${event}"${describePartial(partial)}, but found one at index ${offending}.`);
583
- return chain;
584
- }
585
- };
586
- return chain;
587
- }
588
- //#endregion
589
- //#region src/plugins/log/api.ts
590
- /**
591
- * @file log plugin — API factory.
592
- *
593
- * Builds the `LogApi` over the plugin's `{ config, state }` core context:
594
- * the leveled loggers (via a shared `append`), the frozen `trace()` snapshot,
595
- * the live `expect()` chain, `addSink`, and `reset`.
596
- */
597
- /**
598
- * Append a new entry to the trace and fan it out to every sink in order.
599
- *
600
- * @param state - The mutable log state to append to.
601
- * @param level - Severity level for the entry.
602
- * @param event - Event identifier.
603
- * @param data - Optional structured payload.
604
- * @example
605
- * ```ts
606
- * append(state, "info", "content:ready", { count: 12 });
607
- * ```
608
- */
609
- function append(state, level, event, data) {
610
- const entry = {
611
- level,
612
- event,
613
- data,
614
- ts: Date.now()
615
- };
616
- state.entries.push(entry);
617
- for (const sink of state.sinks) sink.write(entry);
618
- }
619
- /**
620
- * Tests whether a value is a non-null, non-array plain object.
621
- *
622
- * @param value - The value to test.
623
- * @returns `true` when `value` is a non-null object that is not an array.
624
- * @example
625
- * ```ts
626
- * isPlainObject({ a: 1 }); // true
627
- * isPlainObject([1]); // false
628
- * ```
629
- */
630
- function isPlainObject(value) {
631
- return typeof value === "object" && value !== null && !Array.isArray(value);
632
- }
633
- /**
634
- * Merge an `Error`'s `message`/`stack` into `data` under an `error` key. The
635
- * `error` field is always preserved; only a plain object `data` contributes its
636
- * keys. Non-plain-object `data` (arrays and primitives) is replaced by `{}` —
637
- * its original value is not retained — so the merge target is always a record.
638
- *
639
- * @param data - Original payload (any shape).
640
- * @param error - The originating error to merge.
641
- * @returns A new object carrying any plain-object keys plus the `error` field.
642
- * @example
643
- * ```ts
644
- * mergeError({ target: "cf" }, new Error("boom"));
645
- * // { target: "cf", error: { message: "boom", stack: "..." } }
646
- * ```
647
- */
648
- function mergeError(data, error) {
649
- return {
650
- ...isPlainObject(data) ? data : {},
651
- error: {
652
- message: error.message,
653
- stack: error.stack
654
- }
655
- };
656
- }
657
- /**
658
- * Create the log plugin API surface injected as `ctx.log` / `app.log`.
659
- *
660
- * @param ctx - Core plugin context (`{ config, state }`).
661
- * @returns The {@link LogApi} bound to `ctx.state`.
662
- * @example
663
- * ```ts
664
- * const log = createLogApi(ctx);
665
- * log.info("content:ready", { articleCount: 12 });
666
- * ```
667
- */
668
- function createLogApi(ctx) {
669
- const { state } = ctx;
670
- return {
671
- /**
672
- * Append an `info` entry and fan it out to every sink.
673
- *
674
- * @param event - Event identifier (convention: `domain:action`).
675
- * @param data - Optional structured payload.
676
- * @example
677
- * ```ts
678
- * log.info("content:ready", { count: 12 });
679
- * ```
680
- */
681
- info(event, data) {
682
- append(state, "info", event, data);
683
- },
684
- /**
685
- * Append a `debug` entry and fan it out to every sink.
686
- *
687
- * @param event - Event identifier (convention: `domain:action`).
688
- * @param data - Optional structured payload.
689
- * @example
690
- * ```ts
691
- * log.debug("router:match", { path: "/blog/" });
692
- * ```
693
- */
694
- debug(event, data) {
695
- append(state, "debug", event, data);
696
- },
697
- /**
698
- * Append a `warn` entry and fan it out to every sink.
699
- *
700
- * @param event - Event identifier (convention: `domain:action`).
701
- * @param data - Optional structured payload.
702
- * @example
703
- * ```ts
704
- * log.warn("build:skip", { reason: "no sitemap" });
705
- * ```
706
- */
707
- warn(event, data) {
708
- append(state, "warn", event, data);
709
- },
710
- /**
711
- * Append an `error` entry. When `error` is provided, its `message`/`stack`
712
- * are merged into `data` under an `error` key (existing keys preserved);
713
- * otherwise `data` is recorded as-is.
714
- *
715
- * @param event - Event identifier (convention: `domain:action`).
716
- * @param data - Optional structured payload.
717
- * @param error - Optional originating Error to merge into `data`.
718
- * @example
719
- * ```ts
720
- * log.error("deploy:failed", { target: "cf" }, err);
721
- * ```
722
- */
723
- error(event, data, error) {
724
- append(state, "error", event, error === void 0 ? data : mergeError(data, error));
725
- },
726
- /**
727
- * Return a frozen snapshot (fresh copy) of the entries recorded so far.
728
- *
729
- * @returns A readonly, frozen copy of the recorded entries.
730
- * @example
731
- * ```ts
732
- * const entries = log.trace();
733
- * ```
734
- */
735
- trace() {
736
- return Object.freeze([...state.entries]);
737
- },
738
- /**
739
- * Return a fluent assertion chain bound to the live entries array.
740
- *
741
- * @returns A fresh {@link ExpectChain} reading `state.entries` live.
742
- * @example
743
- * ```ts
744
- * log.expect().toHaveEvent("build:complete");
745
- * ```
746
- */
747
- expect() {
748
- return createExpectChain(state.entries);
749
- },
750
- /**
751
- * Register an additional output sink at runtime.
752
- *
753
- * @param sink - The sink to add to the fan-out list.
754
- * @example
755
- * ```ts
756
- * log.addSink({ write: (e) => stream.write(JSON.stringify(e)) });
757
- * ```
758
- */
759
- addSink(sink) {
760
- state.sinks.push(sink);
761
- },
762
- /**
763
- * Clear all recorded entries while keeping registered sinks.
764
- *
765
- * @example
766
- * ```ts
767
- * log.reset();
768
- * ```
769
- */
770
- reset() {
771
- state.entries.length = 0;
772
- }
773
- };
774
- }
775
- //#endregion
776
- //#region src/plugins/log/sinks.ts
777
- /** Severity rank for threshold comparison (higher = more severe). */
778
- const LEVEL_RANK = {
779
- debug: 10,
780
- info: 20,
781
- warn: 30,
782
- error: 40
783
- };
784
- /**
785
- * Build the console sink: routes entries by channel — `error` → `console.error`,
786
- * `warn` → `console.warn`, and `debug`/`info` → `console.log`. The full entry
787
- * object is forwarded so the console serializes its `event` and `data`. Entries
788
- * below `minLevel` are dropped (the in-memory trace still records everything).
789
- *
790
- * @param minLevel - Lowest severity to print. Defaults to `"debug"` (print all).
791
- * @returns A {@link LogSink} that writes to the matching `console` channel.
792
- * @example
793
- * ```ts
794
- * state.sinks.push(consoleSink("info")); // suppress debug spam
795
- * ```
796
- */
797
- function consoleSink(minLevel = "debug") {
798
- const threshold = LEVEL_RANK[minLevel];
799
- return {
800
- /**
801
- * Route a single entry to the console channel matching its level.
802
- *
803
- * @param entry - The entry to emit.
804
- * @example
805
- * ```ts
806
- * sink.write({ level: "warn", event: "build:skip", ts: Date.now() });
807
- * ```
808
- */
809
- write(entry) {
810
- if (LEVEL_RANK[entry.level] < threshold) return;
811
- if (entry.level === "error") console.error(entry);
812
- else if (entry.level === "warn") console.warn(entry);
813
- else console.log(entry);
814
- } };
815
- }
816
- /**
817
- * Install mode-selected default sinks at onInit. The in-memory trace is always
818
- * on (`state.entries`); the console sink is added only in dev/production. `dev`
819
- * prints everything (debug+); `production` prints `info`+ only, so the per-phase
820
- * `debug` events (build:bundle, build:pages, …) don't spam a prod build. Both
821
- * modes still record all levels in the in-memory trace.
822
- *
823
- * @param ctx - Core plugin context (`{ config, state }`).
824
- * @param ctx.config - Resolved log config (`{ mode }`).
825
- * @param ctx.state - Mutable log state (`{ entries, sinks }`).
826
- * @example
827
- * ```ts
828
- * // "dev" -> [consoleSink("debug")]; "production" -> [consoleSink("info")]; "test"/"silent" -> []
829
- * ```
830
- */
831
- function installDefaultSinks(ctx) {
832
- if (ctx.config.mode === "dev") ctx.state.sinks.push(consoleSink("debug"));
833
- else if (ctx.config.mode === "production") ctx.state.sinks.push(consoleSink("info"));
834
- }
835
- //#endregion
836
- //#region src/plugins/log/state.ts
837
- /**
838
- * Create fresh log state: an empty append-only trace and an empty sink list.
839
- * No module-level singletons — guarantees per-`createApp` isolation (two
840
- * `createApp` calls never share `entries` or `sinks`).
841
- *
842
- * @param _ctx - Core plugin context (`{ config }`); unused at construction.
843
- * @returns A fresh `LogState` with empty `entries` and `sinks` arrays.
844
- * @example
845
- * ```ts
846
- * const state = createLogState({ config: { mode: "test" } }); // { entries: [], sinks: [] }
847
- * ```
848
- */
849
- function createLogState(_ctx) {
850
- return {
851
- entries: [],
852
- sinks: []
853
- };
854
- }
855
- /**
856
- * Core logging plugin — always-on in-memory trace + `expect()` event-trace DSL.
857
- * API injected as `ctx.log` on every regular plugin and surfaced as `app.log`.
858
- * No depends / events / hooks (core plugin per spec/03 §5).
859
- *
860
- * @see README.md
861
- */
862
- const logPlugin = (0, _moku_labs_core.createCorePlugin)("log", {
863
- config: { mode: "production" },
864
- createState: createLogState,
865
- api: createLogApi,
866
- onInit: installDefaultSinks
867
- });
868
- //#endregion
869
45
  //#region src/config.ts
870
46
  /**
871
47
  * @file Framework configuration — Config + Events types, core plugin registration.
@@ -887,7 +63,7 @@ const coreConfig = (0, _moku_labs_core.createCoreConfig)("web", {
887
63
  stage: "production",
888
64
  mode: "hybrid"
889
65
  },
890
- plugins: [logPlugin, envPlugin],
66
+ plugins: [_moku_labs_common.logPlugin, _moku_labs_common.envPlugin],
891
67
  pluginConfigs: { log: { mode: "production" } }
892
68
  });
893
69
  /**
@@ -10148,7 +9324,7 @@ function spaEvents(register) {
10148
9324
  }
10149
9325
  //#endregion
10150
9326
  //#region src/plugins/spa/types.ts
10151
- var types_exports$9 = /* @__PURE__ */ require_convention.__exportAll({ COMPONENT_HOOK_NAMES: () => COMPONENT_HOOK_NAMES });
9327
+ var types_exports$7 = /* @__PURE__ */ require_convention.__exportAll({ COMPONENT_HOOK_NAMES: () => COMPONENT_HOOK_NAMES });
10152
9328
  /** Allowed hook names — single source of truth for fail-fast validation. */
10153
9329
  const COMPONENT_HOOK_NAMES = [
10154
9330
  "onCreate",
@@ -11484,176 +10660,11 @@ var types_exports$3 = /* @__PURE__ */ require_convention.__exportAll({});
11484
10660
  //#region src/plugins/deploy/types.ts
11485
10661
  var types_exports$4 = /* @__PURE__ */ require_convention.__exportAll({});
11486
10662
  //#endregion
11487
- //#region src/plugins/env/types.ts
11488
- var types_exports$5 = /* @__PURE__ */ require_convention.__exportAll({});
11489
- //#endregion
11490
10663
  //#region src/plugins/head/types.ts
11491
- var types_exports$6 = /* @__PURE__ */ require_convention.__exportAll({});
11492
- //#endregion
11493
- //#region src/plugins/log/types.ts
11494
- var types_exports$7 = /* @__PURE__ */ require_convention.__exportAll({});
10664
+ var types_exports$5 = /* @__PURE__ */ require_convention.__exportAll({});
11495
10665
  //#endregion
11496
10666
  //#region src/plugins/router/types.ts
11497
- var types_exports$8 = /* @__PURE__ */ require_convention.__exportAll({});
11498
- //#endregion
11499
- //#region src/plugins/env/providers.ts
11500
- /**
11501
- * @file env plugin — built-in providers: dotenv, processEnv, cloudflareBindings.
11502
- */
11503
- /** Default dotenv file path: optional local overrides. */
11504
- const DEFAULT_DOTENV_PATH = ".env.local";
11505
- /** Property on `globalThis` that the consumer sets per Cloudflare request. */
11506
- const CLOUDFLARE_GLOBAL = "__CLOUDFLARE_ENV__";
11507
- /** `String.indexOf` sentinel meaning "no `=` separator on this line". */
11508
- const NO_SEPARATOR = -1;
11509
- /**
11510
- * Strips a single matching pair of surrounding double or single quotes from a
11511
- * value. Leaves unquoted values (and trailing inline comments) untouched.
11512
- *
11513
- * @param value - The already-trimmed raw value.
11514
- * @returns The value with one outer quote pair removed, if present.
11515
- * @example
11516
- * ```ts
11517
- * stripQuotes('"a"'); // "a"
11518
- * stripQuotes("plain # c"); // "plain # c"
11519
- * ```
11520
- */
11521
- function stripQuotes(value) {
11522
- if (value.length < 2) return value;
11523
- const first = value[0];
11524
- const last = value.at(-1);
11525
- if ((first === "\"" || first === "'") && first === last) return value.slice(1, -1);
11526
- return value;
11527
- }
11528
- /**
11529
- * Reports whether a trimmed line carries no assignment — a blank line or a
11530
- * full-line `#` comment — and should be skipped by the parser.
11531
- *
11532
- * @param trimmed - A whitespace-trimmed line from the dotenv text.
11533
- * @returns `true` when the line is empty or a comment.
11534
- * @example
11535
- * ```ts
11536
- * isIgnoredLine(""); // true
11537
- * isIgnoredLine("# note"); // true
11538
- * isIgnoredLine("A=1"); // false
11539
- * ```
11540
- */
11541
- function isIgnoredLine(trimmed) {
11542
- return trimmed === "" || trimmed.startsWith("#");
11543
- }
11544
- /**
11545
- * Parses `.env`-style text into a flat record. Handles CRLF/LF, blank lines,
11546
- * full-line `#` comments, first-`=` splitting, key/value trimming, and a single
11547
- * outer quote pair. Does not strip trailing inline comments on unquoted values.
11548
- *
11549
- * @param text - The raw file contents.
11550
- * @returns A flat record of parsed key/value pairs.
11551
- * @example
11552
- * ```ts
11553
- * parseDotenv('A=1\nB="two"'); // { A: "1", B: "two" }
11554
- * ```
11555
- */
11556
- function parseDotenv(text) {
11557
- const out = {};
11558
- for (const line of text.split(/\r?\n/)) {
11559
- const trimmed = line.trim();
11560
- if (isIgnoredLine(trimmed)) continue;
11561
- const eq = trimmed.indexOf("=");
11562
- if (eq === NO_SEPARATOR) continue;
11563
- const key = trimmed.slice(0, eq).trim();
11564
- out[key] = stripQuotes(trimmed.slice(eq + 1).trim());
11565
- }
11566
- return out;
11567
- }
11568
- /**
11569
- * A zero-dependency `.env`-style provider that re-reads and re-parses the file
11570
- * from disk on every `load()`. Missing file resolves to `{}` (optional
11571
- * overrides). Strips a single outer quote pair; does not strip trailing inline
11572
- * comments on unquoted values.
11573
- *
11574
- * @param path - Path to the dotenv file. Defaults to `.env.local`.
11575
- * @returns An {@link EnvProvider} named `dotenv:<path>` that reads fresh per call.
11576
- * @example
11577
- * ```ts
11578
- * const provider = dotenv(".env.local");
11579
- * provider.load(); // { PUBLIC_API_URL: "/api", ... }
11580
- * ```
11581
- */
11582
- function dotenv(path = DEFAULT_DOTENV_PATH) {
11583
- return {
11584
- name: `dotenv:${path}`,
11585
- /**
11586
- * Reads and parses the dotenv file fresh from disk; `{}` if it is missing.
11587
- *
11588
- * @returns The parsed environment record, or `{}` when the file is absent.
11589
- * @example
11590
- * ```ts
11591
- * dotenv(".env.local").load();
11592
- * ```
11593
- */
11594
- load() {
11595
- if (!(0, node_fs.existsSync)(path)) return {};
11596
- return parseDotenv((0, node_fs.readFileSync)(path, "utf8"));
11597
- }
11598
- };
11599
- }
11600
- /**
11601
- * A provider that returns a shallow copy of `process.env` at `load()` time.
11602
- *
11603
- * @returns An {@link EnvProvider} named `process-env`.
11604
- * @example
11605
- * ```ts
11606
- * const provider = processEnv();
11607
- * provider.load().HOME; // current process value
11608
- * ```
11609
- */
11610
- function processEnv() {
11611
- return {
11612
- name: "process-env",
11613
- /**
11614
- * Returns a shallow copy of `process.env` at call time.
11615
- *
11616
- * @returns A fresh shallow copy of `process.env`.
11617
- * @example
11618
- * ```ts
11619
- * processEnv().load();
11620
- * ```
11621
- */
11622
- load() {
11623
- return { ...process.env };
11624
- }
11625
- };
11626
- }
11627
- /**
11628
- * A provider that reads live, per-request Cloudflare bindings from
11629
- * `globalThis.__CLOUDFLARE_ENV__` at `load()` time (`?? {}` when absent). Never
11630
- * caches the binding object; the consumer owns the global's request lifecycle.
11631
- *
11632
- * @returns An {@link EnvProvider} named `cloudflare`.
11633
- * @example
11634
- * ```ts
11635
- * globalThis.__CLOUDFLARE_ENV__ = env; // set by the request handler
11636
- * const provider = cloudflareBindings();
11637
- * provider.load(); // reads the current request's bindings
11638
- * ```
11639
- */
11640
- function cloudflareBindings() {
11641
- return {
11642
- name: "cloudflare",
11643
- /**
11644
- * Reads `globalThis.__CLOUDFLARE_ENV__` fresh, never caching the bindings.
11645
- *
11646
- * @returns The current Cloudflare bindings, or `{}` when the global is unset.
11647
- * @example
11648
- * ```ts
11649
- * cloudflareBindings().load();
11650
- * ```
11651
- */
11652
- load() {
11653
- return globalThis[CLOUDFLARE_GLOBAL] ?? {};
11654
- }
11655
- };
11656
- }
10667
+ var types_exports$6 = /* @__PURE__ */ require_convention.__exportAll({});
11657
10668
  //#endregion
11658
10669
  //#region node_modules/unist-util-stringify-position/lib/index.js
11659
10670
  /**
@@ -13884,43 +12895,41 @@ Object.defineProperty(exports, "Deploy", {
13884
12895
  }
13885
12896
  });
13886
12897
  exports.EmbedFacadeButton = EmbedFacadeButton;
13887
- Object.defineProperty(exports, "Env", {
12898
+ exports.GalleryTrack = GalleryTrack;
12899
+ Object.defineProperty(exports, "Head", {
13888
12900
  enumerable: true,
13889
12901
  get: function() {
13890
12902
  return types_exports$5;
13891
12903
  }
13892
12904
  });
13893
- exports.GalleryTrack = GalleryTrack;
13894
- Object.defineProperty(exports, "Head", {
12905
+ Object.defineProperty(exports, "Router", {
13895
12906
  enumerable: true,
13896
12907
  get: function() {
13897
12908
  return types_exports$6;
13898
12909
  }
13899
12910
  });
13900
- Object.defineProperty(exports, "Log", {
12911
+ Object.defineProperty(exports, "Spa", {
13901
12912
  enumerable: true,
13902
12913
  get: function() {
13903
12914
  return types_exports$7;
13904
12915
  }
13905
12916
  });
13906
- Object.defineProperty(exports, "Router", {
12917
+ Object.defineProperty(exports, "browserEnv", {
13907
12918
  enumerable: true,
13908
12919
  get: function() {
13909
- return types_exports$8;
12920
+ return _moku_labs_common.browserEnv;
13910
12921
  }
13911
12922
  });
13912
- Object.defineProperty(exports, "Spa", {
13913
- enumerable: true,
13914
- get: function() {
13915
- return types_exports$9;
13916
- }
13917
- });
13918
- exports.browserEnv = browserEnv;
13919
12923
  exports.buildArticleHead = buildArticleHead;
13920
12924
  exports.buildPlugin = buildPlugin;
13921
12925
  exports.canonical = canonical;
13922
12926
  exports.cliPlugin = cliPlugin;
13923
- exports.cloudflareBindings = cloudflareBindings;
12927
+ Object.defineProperty(exports, "cloudflareBindings", {
12928
+ enumerable: true,
12929
+ get: function() {
12930
+ return _moku_labs_common.cloudflareBindings;
12931
+ }
12932
+ });
13924
12933
  exports.contentPlugin = contentPlugin;
13925
12934
  exports.createApp = createApp;
13926
12935
  exports.createComponent = createComponent;
@@ -13929,8 +12938,18 @@ exports.createUrls = createUrls;
13929
12938
  exports.dataPlugin = dataPlugin;
13930
12939
  exports.defineRoutes = defineRoutes;
13931
12940
  exports.deployPlugin = deployPlugin;
13932
- exports.dotenv = dotenv;
13933
- exports.envPlugin = envPlugin;
12941
+ Object.defineProperty(exports, "dotenv", {
12942
+ enumerable: true,
12943
+ get: function() {
12944
+ return _moku_labs_common.dotenv;
12945
+ }
12946
+ });
12947
+ Object.defineProperty(exports, "envPlugin", {
12948
+ enumerable: true,
12949
+ get: function() {
12950
+ return _moku_labs_common.envPlugin;
12951
+ }
12952
+ });
13934
12953
  exports.feedLink = feedLink;
13935
12954
  exports.fileSystemContent = fileSystemContent;
13936
12955
  exports.headPlugin = headPlugin;
@@ -13938,10 +12957,20 @@ exports.hreflang = hreflang;
13938
12957
  exports.i18nPlugin = i18nPlugin;
13939
12958
  exports.jsonLd = jsonLd;
13940
12959
  exports.lazyEmbed = lazyEmbed;
13941
- exports.logPlugin = logPlugin;
12960
+ Object.defineProperty(exports, "logPlugin", {
12961
+ enumerable: true,
12962
+ get: function() {
12963
+ return _moku_labs_common.logPlugin;
12964
+ }
12965
+ });
13942
12966
  exports.meta = meta;
13943
12967
  exports.og = og;
13944
- exports.processEnv = processEnv;
12968
+ Object.defineProperty(exports, "processEnv", {
12969
+ enumerable: true,
12970
+ get: function() {
12971
+ return _moku_labs_common.processEnv;
12972
+ }
12973
+ });
13945
12974
  exports.route = route;
13946
12975
  exports.routerPlugin = routerPlugin;
13947
12976
  exports.sitePlugin = sitePlugin;