Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 | 5x 5x 2x 1x 7x 5x 5x 5x 5x 5x 5x 5x 147x 119x 28x 2x 26x 36x 33x 3x 3x 3x 3x 3x 39x 39x 39x 18x 18x 18x 2x 2x 18x 19x 18x 18x 18x 1x 17x 17x 5x 44x 44x 6x 38x 10x 10x 15x 15x 13x 10x 28x 28x 28x 28x 27x 27x 27x 27x 27x 27x 27x 25x 25x 25x 27x 27x 27x 22x 22x 27x 42x 42x 10x 10x 10x 32x 17x 2x 15x 14x 14x 25x 3x 3x 3x 1x 1x 1x 1x 25x 8x 54x 54x | /**
* Simple state management for server-side rendering
* This is mainly for component state during rendering
*/
const globalState = new Map();
/**
* Creates a state container for a request/render cycle
* @param {Object} initialState - Initial state object
* @returns {Object} State container
*/
export function createState(initialState = {}) {
const state = new Map(Object.entries(initialState));
return {
get(key) {
return state.get(key);
},
set(key, value) {
state.set(key, value);
return this;
},
has(key) {
return state.has(key);
},
delete(key) {
return state.delete(key);
},
clear() {
state.clear();
return this;
},
toObject() {
return Object.fromEntries(state);
},
// For debugging
_internal: state
};
}
/**
* Global state for sharing data across components during SSR.
*
* This store is process-wide: every request sees it. It is also the fallback
* useContext() reads when no context has been provided for a key, so it suits
* application-wide defaults, never request data.
*/
export const globalStateManager = {
set(key, value) {
globalState.set(key, value);
},
get(key) {
return globalState.get(key);
},
has(key) {
return globalState.has(key);
},
clear() {
globalState.clear();
},
// Create isolated state for each request
createRequestState() {
return createState();
}
};
// ============================================================================
// Context API
// ============================================================================
//
// A scope is an immutable Map from context key to a linked stack entry
// `{ value, previous }`. A holder `{ scope, owned }` points at the current
// scope.
//
// On Node the holder lives in an AsyncLocalStorage, so it follows each
// request's async execution:
//
// - runWithContext() (and a provider) runs its callback with a fresh holder
// that it owns. Inside it every change updates that holder in place, so
// the value stays put across the awaits and yields of an async or
// streaming render, and nothing leaks out of it.
// - Outside any owned holder there is nothing request-scoped to write to, so
// providing a value throws (see setScope()).
//
// Browsers have no AsyncLocalStorage. There a single module holder is updated
// in place, which is exact for synchronous rendering; a value read after an
// `await` sees whatever is current at that point.
const EMPTY_SCOPE = new Map();
function createAsyncStorage() {
try {
// Never a static import: this module also runs in browsers.
const asyncHooks = globalThis.process?.getBuiltinModule?.('node:async_hooks');
const AsyncLocalStorage = asyncHooks?.AsyncLocalStorage;
return typeof AsyncLocalStorage === 'function' ? new AsyncLocalStorage() : null;
} catch {
return null;
}
}
const asyncStorage = createAsyncStorage();
/** The holder used when AsyncLocalStorage is unavailable. */
const syncHolder = { scope: EMPTY_SCOPE, owned: true };
function currentHolder() {
return asyncStorage ? asyncStorage.getStore() : syncHolder;
}
function currentScope() {
return currentHolder()?.scope ?? EMPTY_SCOPE;
}
/**
* Make `scope` current in `holder` (the scope of the enclosing
* runWithContext() call, or the browser's single holder).
*
* There is deliberately no fallback outside runWithContext() on the server.
* AsyncLocalStorage#enterWith() attached the value to the caller's async
* context, and a request's async context is shared with the next request
* on the same keep-alive connection: the value leaked to other users (and
* a module-level store would leak to every request).
*/
function setScope(scope, holder = currentHolder()) {
if (!holder?.owned) {
throw new Error(
'Context can only be provided inside runWithContext() on the server: outside it the value ' +
'would leak into other requests. Wrap each request or render: runWithContext(() => ...).'
);
}
holder.scope = scope;
}
/**
* Run `fn(...args)` with `scope` current in a holder of its own, restoring the
* previous scope afterwards.
*/
function runInScope(scope, fn, args) {
if (asyncStorage) {
return asyncStorage.run({ scope, owned: true }, fn, ...args);
}
const previous = syncHolder.scope;
syncHolder.scope = scope;
try {
return fn(...args);
} finally {
syncHolder.scope = previous;
}
}
function withValue(scope, key, value) {
const next = new Map(scope);
next.set(key, { value, previous: scope.get(key) });
return next;
}
/**
* Run `fn` in a fresh, isolated context scope — one per request or render.
*
* Nothing provided inside `fn` is visible outside it and nothing provided
* outside is visible inside. On Node this holds across `await`s, so wrap each
* request (or each `renderToStream()` consumer) in it.
*
* @template T
* @param {() => T} fn - Work to run, typically a request handler or a render
* @param {Object} [values] - Initial context values, keyed by context key
* @returns {T} Whatever `fn` returns (a promise for an async `fn`)
*/
export function runWithContext(fn, values) {
Iif (typeof fn !== 'function') {
throw new TypeError(`runWithContext() requires a function, received: ${typeof fn}`);
}
let scope = EMPTY_SCOPE;
if (values && typeof values === 'object') {
for (const [key, value] of Object.entries(values)) {
scope = withValue(scope, key, value);
}
}
return runInScope(scope, fn, []);
}
/**
* Provide a context value for the rest of the current runWithContext() scope,
* remembering the previous one so {@link restoreContext} can unwind it.
*
* On Node it must be called inside {@link runWithContext} (it throws
* otherwise); a concurrent request does not see the value, even across
* `await`s. In browsers it may be called anywhere.
*
* @throws {Error} On Node, when called outside runWithContext()
*
* @param {string} key - Context key
* @param {*} value - Context value
*/
export function provideContext(key, value) {
setScope(withValue(currentScope(), key, value));
}
/**
* Create a context provider component.
*
* The provider is a zero-argument function component. When the renderer calls
* it, it evaluates the function components and function-valued props below
* it with the value provided, and returns the resulting plain tree; its
* siblings do not see the value. Nothing is pre-rendered, so the renderer
* escapes the children exactly once. Values read later, such as in an event
* handler, do not see it.
*
* Called with a render function instead, the provider runs
* `renderFunction(children)` with the context provided and returns its result.
* On Node an async render function keeps the context across its `await`s.
*
* @param {string} key - Context key
* @param {*} value - Context value
* @param {*} children - Children to render with context
* @returns {Function} Context provider component
*/
export function createContextProvider(key, value, children) {
// Rest parameters keep `length` at 0, so a renderer calls this as an
// ordinary function component.
function contextProvider(...args) {
const renderFunction = args[0];
const scope = withValue(currentScope(), key, value);
if (typeof renderFunction === 'function') {
return runInScope(scope, renderFunction, [children]);
}
// Evaluate the function components below the provider inside its
// scope, and hand the renderer the resulting plain tree. The scope
// is restored even when a child throws; enter/leave marker
// components used to leave the value set for the next request when
// a child threw before the "leave" marker ran.
return runInScope(scope, resolveComponents, [children]);
}
return contextProvider;
}
const TAG_NAME = /^[a-zA-Z][a-zA-Z0-9-]*$/;
/**
* Call the function components in a tree the way the renderer does (no
* arguments, following returned functions), so context reads happen now.
* Unchanged nodes are returned as they are (trusted-content markers keep
* their brand); event handlers are props and are never called.
*/
function resolveComponents(node, depth = 0) {
Iif (depth > 1000) return node;
if (typeof node === 'function') {
return resolveComponents(node(), depth + 1);
}
if (Array.isArray(node)) {
let changed = false;
const resolved = node.map((child) => {
const next = resolveComponents(child, depth + 1);
if (next !== child) changed = true;
return next;
});
return changed ? resolved : node;
}
Iif (!node || typeof node !== 'object') return node;
Iif (node.__isLazy === true && typeof node.evaluate === 'function') {
return resolveComponents(node.evaluate(), depth + 1);
}
const tags = Object.keys(node);
if (tags.length === 0 || !tags.every((tag) => TAG_NAME.test(tag))) return node;
let changed = false;
const resolved = {};
for (const tag of tags) {
let content = node[tag];
Iif (typeof content === 'function') {
content = resolveComponents(content(), depth + 1);
}
Eif (content && typeof content === 'object' && !Array.isArray(content) && !isTrusted(content)) {
content = resolveProps(content, depth);
}
if (content !== node[tag]) changed = true;
resolved[tag] = content;
}
return changed ? resolved : node;
}
function isTrusted(value) {
return value[Symbol.for('coherent.js.trustedContent')] === true;
}
/**
* Evaluate the function-valued props the renderer would call (`text`,
* `html` and attributes other than `on*` event handlers) and the children.
* An attribute function that throws is left for the renderer, which
* reports it and renders an empty value.
*/
function resolveProps(props, depth) {
let next = props;
const set = (key, value) => {
if (next === props) next = { ...props };
next[key] = value;
};
for (const key of Object.keys(props)) {
const value = props[key];
if (key === 'children') {
Eif (value !== undefined && value !== null) {
const children = resolveComponents(value, depth + 1);
if (children !== value) set(key, children);
}
} else if (typeof value === 'function' && key !== 'key') {
if (key === 'text' || key === 'html') {
set(key, value());
} else if (!key.startsWith('on')) {
try {
set(key, value());
} catch {
// left in place for the renderer
}
}
}
}
return next;
}
/**
* Restore context to its previous value
* @param {string} key - Context key
*/
export function restoreContext(key) {
const scope = currentScope();
const entry = scope.get(key);
if (!entry) return;
const next = new Map(scope);
Iif (entry.previous) {
next.set(key, entry.previous);
} else {
next.delete(key);
}
setScope(next);
}
/**
* Drop every context provided in the current execution.
*
* Values set through {@link globalStateManager} are not contexts and are left
* alone; useContext() falls back to them again.
*/
export function clearAllContexts() {
if (currentScope().size > 0) {
setScope(EMPTY_SCOPE);
}
}
/**
* Context consumer to access provided context
*
* Falls back to {@link globalStateManager} when no context has been provided
* for `key`.
*
* @param {string} key - Context key
* @returns {*} Context value
*/
export function useContext(key) {
const entry = currentScope().get(key);
return entry ? entry.value : globalState.get(key);
}
|