brumate 0.0.1 → 0.1.1

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.
Files changed (81) hide show
  1. package/README.md +43 -72
  2. package/dist/boot-DN1ZU8Hg.d.ts +37 -0
  3. package/dist/cli.js +2 -2
  4. package/dist/{client-DuDTDePF.d.ts → client-DwJInP_a.d.ts} +133 -44
  5. package/dist/client-routes-DakuM32C.js +94 -0
  6. package/dist/client-routes-DakuM32C.js.map +1 -0
  7. package/dist/{cookies-rgIAc8IE.js → cookies-Av5WFmcf.js} +18 -8
  8. package/dist/cookies-Av5WFmcf.js.map +1 -0
  9. package/dist/{devtools-Bm8cS7hX.js → devtools-BKjnHrnv.js} +10 -5
  10. package/dist/devtools-BKjnHrnv.js.map +1 -0
  11. package/dist/{devtools-panel-CTbDSBBA.js → devtools-panel-AWOn0VK2.js} +23 -26
  12. package/dist/devtools-panel-AWOn0VK2.js.map +1 -0
  13. package/dist/{files-D_JUcSU5.js → files-DdT84mPy.js} +22 -3
  14. package/dist/{files-D_JUcSU5.js.map → files-DdT84mPy.js.map} +1 -1
  15. package/dist/{html-CxWpXngy.js → html-DEeoepg3.js} +47 -10
  16. package/dist/html-DEeoepg3.js.map +1 -0
  17. package/dist/{html-DV-Tezgq.d.ts → html-Du8jY2Cc.d.ts} +14 -2
  18. package/dist/index.d.ts +65 -6
  19. package/dist/index.js +20 -4
  20. package/dist/index.js.map +1 -1
  21. package/dist/{inspect-CGCWfaEx.js → inspect-BPchdWbU.js} +887 -172
  22. package/dist/inspect-BPchdWbU.js.map +1 -0
  23. package/dist/loader-Dc9OwY5I.js +101 -0
  24. package/dist/loader-Dc9OwY5I.js.map +1 -0
  25. package/dist/{navigate-C5dP89YL.js → navigate-CzLjnoPH.js} +112 -59
  26. package/dist/navigate-CzLjnoPH.js.map +1 -0
  27. package/dist/{produce-BjQGMpqL.d.ts → produce-CtZ32UGG.d.ts} +13 -3
  28. package/dist/{rpc-B86KKjzx.js → rpc-9fSqL_YK.js} +57 -12
  29. package/dist/rpc-9fSqL_YK.js.map +1 -0
  30. package/dist/runtime/client.d.ts +4 -4
  31. package/dist/runtime/client.js +599 -306
  32. package/dist/runtime/client.js.map +1 -1
  33. package/dist/runtime/devtools.d.ts +3 -1
  34. package/dist/runtime/devtools.js +1 -1
  35. package/dist/runtime/hot.d.ts +1 -1
  36. package/dist/runtime/hot.js +9 -5
  37. package/dist/runtime/hot.js.map +1 -1
  38. package/dist/runtime/html.d.ts +2 -2
  39. package/dist/runtime/html.js +1 -1
  40. package/dist/runtime/loader.d.ts +12 -2
  41. package/dist/runtime/loader.js +3 -1
  42. package/dist/runtime/server.d.ts +4 -4
  43. package/dist/runtime/server.js +5 -5
  44. package/dist/runtime/signals.d.ts +2 -2
  45. package/dist/runtime/signals.js +5 -5
  46. package/dist/runtime/signals.js.map +1 -1
  47. package/dist/runtime/static-loader.d.ts +3 -0
  48. package/dist/runtime/static-loader.js +1 -0
  49. package/dist/runtime/testing.d.ts +21 -2
  50. package/dist/runtime/testing.js +83 -7
  51. package/dist/runtime/testing.js.map +1 -1
  52. package/dist/{server-sQCvduOz.d.ts → server-BxqjLUnV.d.ts} +211 -20
  53. package/dist/{server-CX3JnPCs.js → server-DZsgnPKS.js} +595 -185
  54. package/dist/server-DZsgnPKS.js.map +1 -0
  55. package/dist/shared-CWYOd0H3.js +40 -0
  56. package/dist/shared-CWYOd0H3.js.map +1 -0
  57. package/dist/static-loader-BcFh4ebX.d.ts +11 -0
  58. package/dist/static-loader-ClNkHZGn.js +185 -0
  59. package/dist/static-loader-ClNkHZGn.js.map +1 -0
  60. package/dist/stream-bgNCMcaA.js +280 -0
  61. package/dist/stream-bgNCMcaA.js.map +1 -0
  62. package/dist/vite.d.ts +30 -5
  63. package/dist/vite.js +501 -62
  64. package/dist/vite.js.map +1 -1
  65. package/package.json +7 -2
  66. package/types.d.ts +5 -0
  67. package/dist/cookies-rgIAc8IE.js.map +0 -1
  68. package/dist/devtools-Bm8cS7hX.js.map +0 -1
  69. package/dist/devtools-panel-CTbDSBBA.js.map +0 -1
  70. package/dist/html-CxWpXngy.js.map +0 -1
  71. package/dist/inspect-CGCWfaEx.js.map +0 -1
  72. package/dist/loader-BUhNqDHw.d.ts +0 -30
  73. package/dist/loader-py4qu6tQ.js +0 -215
  74. package/dist/loader-py4qu6tQ.js.map +0 -1
  75. package/dist/navigate-C5dP89YL.js.map +0 -1
  76. package/dist/rpc-B86KKjzx.js.map +0 -1
  77. package/dist/server-CX3JnPCs.js.map +0 -1
  78. package/dist/shared-BE_oBSDM.js +0 -176
  79. package/dist/shared-BE_oBSDM.js.map +0 -1
  80. package/dist/stream-cvhqOzfs.js +0 -145
  81. package/dist/stream-cvhqOzfs.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cookies-Av5WFmcf.js","names":[],"sources":["../src/runtime/cookies.ts"],"sourcesContent":["// Cookies and sessions, for server functions, rendering, middleware and\n// endpoints. They read the request of a `RequestEvent` and write `set-cookie`\n// headers on its response.\n\nimport type { RequestEvent } from './request.ts';\n\nexport interface CookieOptions {\n /** Seconds until the cookie expires. Without it, the cookie lasts until the browser closes. */\n maxAge?: number;\n expires?: Date;\n /** Defaults to `/`. */\n path?: string;\n domain?: string;\n /** Defaults to true when the request is HTTPS. */\n secure?: boolean;\n /** Keeps the cookie from browser code. Defaults to true. */\n httpOnly?: boolean;\n /** Defaults to `lax`. */\n sameSite?: 'strict' | 'lax' | 'none';\n}\n\n/** Reads the cookies of a `cookie` header. */\nexport function parseCookies(header: string | null): Record<string, string> {\n const result: Record<string, string> = {};\n for (const part of (header ?? '').split(';')) {\n const index = part.indexOf('=');\n if (index === -1) {\n continue;\n }\n const name = part.slice(0, index).trim();\n if (name && !(name in result)) {\n const value = part.slice(index + 1).trim();\n try {\n result[name] = decodeURIComponent(value);\n } catch {\n result[name] = value;\n }\n }\n }\n return result;\n}\n\n/** Writes a `set-cookie` header value. */\nexport function serializeCookie(name: string, value: string, options: CookieOptions = {}): string {\n if (!/^[\\w!#$%&'*+.^`|~-]+$/.test(name)) {\n throw new Error(`\"${name}\" is not a valid cookie name`);\n }\n const parts = [`${name}=${encodeURIComponent(value)}`, `Path=${options.path ?? '/'}`];\n if (options.maxAge !== undefined) {\n parts.push(`Max-Age=${Math.floor(options.maxAge)}`);\n }\n if (options.expires) {\n parts.push(`Expires=${options.expires.toUTCString()}`);\n }\n if (options.domain) {\n parts.push(`Domain=${options.domain}`);\n }\n if (options.httpOnly !== false) {\n parts.push('HttpOnly');\n }\n if (options.secure) {\n parts.push('Secure');\n }\n parts.push(\n `SameSite=${(options.sameSite ?? 'lax').replace(/^./, (letter) => letter.toUpperCase())}`,\n );\n return parts.join('; ');\n}\n\n/** The parsed `cookie` header of each event, with the header it was parsed from. */\nconst parsed = new WeakMap<\n RequestEvent,\n { header: string | null; cookies: Record<string, string> }\n>();\n\n/** The cookies of the request, with the ones that this request set or deleted. */\nexport function getCookies(event: RequestEvent): Record<string, string> {\n const header = event.request.headers.get('cookie');\n let cached = parsed.get(event);\n if (cached?.header !== header) {\n cached = { header, cookies: parseCookies(header) };\n parsed.set(event, cached);\n }\n // A copy, so the caller cannot change the cache.\n const result = { ...cached.cookies };\n for (const [name, value] of event.cookies ?? []) {\n if (value === undefined) {\n delete result[name];\n } else {\n result[name] = value;\n }\n }\n return result;\n}\n\n/** Sets a cookie on the response of an event. See `RequestEvent.setCookie`. */\nexport function setCookie(\n event: RequestEvent,\n name: string,\n value: string,\n options: CookieOptions = {},\n): void {\n const secure = options.secure ?? new URL(event.request.url).protocol === 'https:';\n event.headers.append('set-cookie', serializeCookie(name, value, { ...options, secure }));\n event.cookies ??= new Map();\n event.cookies.set(name, value);\n}\n\n/** Deletes a cookie. Pass the `path` and `domain` that it was set with, if they were not the defaults. */\nexport function deleteCookie(\n event: RequestEvent,\n name: string,\n options: Pick<CookieOptions, 'path' | 'domain'> = {},\n): void {\n // `secure` follows the request, as for a cookie set without it.\n setCookie(event, name, '', { ...options, secure: undefined, maxAge: 0, expires: new Date(0) });\n event.cookies!.set(name, undefined);\n}\n\nexport interface SessionOptions {\n /**\n * Signs the cookie, so a browser cannot change it. Use a random string of\n * at least 32 characters, kept out of the code, such as in an environment\n * variable. A list signs with the first and accepts all, for changing it.\n */\n secret: string | string[];\n /** The name of the cookie. Defaults to `session`. */\n name?: string;\n /** Seconds until the session expires. Defaults to 7 days. */\n maxAge?: number;\n /** Other options of the cookie. */\n cookie?: Omit<CookieOptions, 'maxAge' | 'expires'>;\n}\n\nexport interface Session<T> {\n /** The data of the session, or undefined when there is none, it expired, or its signature does not match. */\n get(event: RequestEvent): Promise<T | undefined>;\n /** Replaces the data of the session, and starts its time again. */\n set(event: RequestEvent, data: T): Promise<void>;\n /** Changes some fields of the data, and returns the new data. */\n update(event: RequestEvent, change: Partial<T>): Promise<T>;\n /** Ends the session. */\n clear(event: RequestEvent): void;\n}\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\nconst keys = new Map<string, Promise<CryptoKey>>();\n\nfunction key(secret: string): Promise<CryptoKey> {\n let promise = keys.get(secret);\n if (!promise) {\n promise = crypto.subtle.importKey(\n 'raw',\n encoder.encode(secret),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign', 'verify'],\n );\n keys.set(secret, promise);\n }\n return promise;\n}\n\nfunction toBase64Url(bytes: Uint8Array): string {\n let text = '';\n for (const byte of bytes) {\n text += String.fromCharCode(byte);\n }\n return btoa(text).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\nfunction fromBase64Url(text: string): Uint8Array<ArrayBuffer> {\n const base64 = text.replace(/-/g, '+').replace(/_/g, '/');\n return Uint8Array.from(atob(base64), (char) => char.charCodeAt(0));\n}\n\n/**\n * A session in a signed cookie. The browser can read the data, but cannot\n * change it, so keep secrets out of it: store an ID, and look the rest up\n * on the server.\n *\n * ```ts\n * export const session = createSession<{ userId: string }>({ secret: process.env.SESSION_SECRET! });\n *\n * async function login(form: FormData) {\n * 'use server';\n * const event = getEvent();\n * await session.set(event, { userId: await checkPassword(form) });\n * }\n * ```\n */\nexport function createSession<T>(options: SessionOptions): Session<T> {\n const secrets = Array.isArray(options.secret) ? options.secret : [options.secret];\n if (secrets.length === 0 || secrets.some((secret) => secret.length < 32)) {\n throw new Error('A session secret needs at least 32 characters');\n }\n const name = options.name ?? 'session';\n const maxAge = options.maxAge ?? 7 * 24 * 60 * 60;\n\n const read = async (event: RequestEvent): Promise<T | undefined> => {\n const value = getCookies(event)[name];\n const dot = value?.lastIndexOf('.') ?? -1;\n if (!value || dot === -1) {\n return undefined;\n }\n const payload = value.slice(0, dot);\n let signature: Uint8Array<ArrayBuffer>;\n try {\n signature = fromBase64Url(value.slice(dot + 1));\n } catch {\n return undefined;\n }\n // Any of the secrets can have signed it, such as an older one while a secret changes.\n const checks = await Promise.all(\n secrets.map(async (secret) =>\n crypto.subtle.verify('HMAC', await key(secret), signature, encoder.encode(payload)),\n ),\n );\n if (!checks.includes(true)) {\n return undefined;\n }\n try {\n const { d: data, e: expires } = JSON.parse(decoder.decode(fromBase64Url(payload))) as {\n d: T;\n e: number;\n };\n return expires > Date.now() ? data : undefined;\n } catch {\n return undefined;\n }\n };\n\n const write = async (event: RequestEvent, data: T): Promise<void> => {\n const payload = toBase64Url(\n encoder.encode(JSON.stringify({ d: data, e: Date.now() + maxAge * 1000 })),\n );\n const signature = new Uint8Array(\n await crypto.subtle.sign('HMAC', await key(secrets[0]!), encoder.encode(payload)),\n );\n const value = `${payload}.${toBase64Url(signature)}`;\n // Browsers drop cookies over about 4 KB.\n if (value.length > 4000) {\n throw new Error(\n `The session is ${value.length} bytes, over the 4000 that a cookie can hold. Store an ID in it instead`,\n );\n }\n setCookie(event, name, value, { ...options.cookie, maxAge });\n };\n\n return {\n get: read,\n set: write,\n async update(event, change) {\n const data = { ...(await read(event)), ...change } as T;\n await write(event, data);\n return data;\n },\n clear: (event) =>\n deleteCookie(event, name, { path: options.cookie?.path, domain: options.cookie?.domain }),\n };\n}\n\n/**\n * The headers of a response for Node's `writeHead`, with each `set-cookie`\n * apart. `Object.fromEntries(headers)` joins them into one, which browsers\n * read as a single cookie.\n */\nexport function toNodeHeaders(headers: Headers): Record<string, string | string[]> {\n const result: Record<string, string | string[]> = Object.fromEntries(headers);\n const cookies = headers.getSetCookie();\n if (cookies.length > 0) {\n result['set-cookie'] = cookies;\n }\n return result;\n}\n"],"mappings":";;AAsBA,SAAgB,aAAa,QAA+C;CAC1E,MAAM,SAAiC,CAAC;CACxC,KAAK,MAAM,SAAS,UAAU,GAAA,CAAI,MAAM,GAAG,GAAG;EAC5C,MAAM,QAAQ,KAAK,QAAQ,GAAG;EAC9B,IAAI,UAAU,IACZ;EAEF,MAAM,OAAO,KAAK,MAAM,GAAG,KAAK,CAAC,CAAC,KAAK;EACvC,IAAI,QAAQ,EAAE,QAAQ,SAAS;GAC7B,MAAM,QAAQ,KAAK,MAAM,QAAQ,CAAC,CAAC,CAAC,KAAK;GACzC,IAAI;IACF,OAAO,QAAQ,mBAAmB,KAAK;GACzC,QAAQ;IACN,OAAO,QAAQ;GACjB;EACF;CACF;CACA,OAAO;AACT;;AAGA,SAAgB,gBAAgB,MAAc,OAAe,UAAyB,CAAC,GAAW;CAChG,IAAI,CAAC,wBAAwB,KAAK,IAAI,GACpC,MAAM,IAAI,MAAM,IAAI,KAAK,6BAA6B;CAExD,MAAM,QAAQ,CAAC,GAAG,KAAK,GAAG,mBAAmB,KAAK,KAAK,QAAQ,QAAQ,QAAQ,KAAK;CACpF,IAAI,QAAQ,WAAW,KAAA,GACrB,MAAM,KAAK,WAAW,KAAK,MAAM,QAAQ,MAAM,GAAG;CAEpD,IAAI,QAAQ,SACV,MAAM,KAAK,WAAW,QAAQ,QAAQ,YAAY,GAAG;CAEvD,IAAI,QAAQ,QACV,MAAM,KAAK,UAAU,QAAQ,QAAQ;CAEvC,IAAI,QAAQ,aAAa,OACvB,MAAM,KAAK,UAAU;CAEvB,IAAI,QAAQ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Aa;CACrC,IAAI,QAAQ,SAAS,GACnB,OAAO,gBAAgB;CAEzB,OAAO;AACT"}
@@ -1,6 +1,12 @@
1
1
  //#region src/runtime/devtools.ts
2
2
  const DEVTOOLS = Symbol.for("brumate.devtools");
3
3
  const MAX_LOG = 300;
4
+ /** The root scope of a scope, whose `m` names its component. */
5
+ function rootOf(scope) {
6
+ let root = scope;
7
+ while (root.p) root = root.p;
8
+ return root;
9
+ }
4
10
  /** A short text for a value in the log. */
5
11
  function preview(value) {
6
12
  if (typeof value === "string") return JSON.stringify(value.length > 40 ? `${value.slice(0, 40)}…` : value);
@@ -48,8 +54,7 @@ function installDevtools(endpoint = "/__brumate/inspect", rpc = "/_brumate") {
48
54
  },
49
55
  write(scope, slot, value) {
50
56
  state.written.add(scope.id);
51
- let root = scope;
52
- while (root.p) root = root.p;
57
+ const root = rootOf(scope);
53
58
  add({
54
59
  kind: "write",
55
60
  text: `scope ${scope.id} slot ${slot} = ${preview(value)}`,
@@ -92,7 +97,7 @@ function installDevtools(endpoint = "/__brumate/inspect", rpc = "/_brumate") {
92
97
  button.title = "Open the brumate devtools";
93
98
  button.setAttribute("style", "position:fixed;right:12px;bottom:12px;z-index:2147483647;font:600 12px ui-monospace,monospace;padding:6px 10px;border-radius:999px;border:1px solid #8884;background:#111;color:#fff;cursor:pointer");
94
99
  button.addEventListener("click", () => {
95
- import("./devtools-panel-CTbDSBBA.js").then(({ togglePanel }) => togglePanel(root, state));
100
+ import("./devtools-panel-AWOn0VK2.js").then(({ togglePanel }) => togglePanel(root, state));
96
101
  });
97
102
  root.append(button);
98
103
  const append = () => {
@@ -103,6 +108,6 @@ function installDevtools(endpoint = "/__brumate/inspect", rpc = "/_brumate") {
103
108
  return state;
104
109
  }
105
110
  //#endregion
106
- export { preview as n, installDevtools as t };
111
+ export { preview as n, rootOf as r, installDevtools as t };
107
112
 
108
- //# sourceMappingURL=devtools-Bm8cS7hX.js.map
113
+ //# sourceMappingURL=devtools-BKjnHrnv.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"devtools-BKjnHrnv.js","names":[],"sources":["../src/runtime/devtools.ts"],"sourcesContent":["// The devtools overlay of development builds. This module only listens to\n// the core and shows a button. The panel loads when the button is pressed,\n// so the page behaves as in production until then.\n\nimport type { DevtoolsHooks, Scope } from './client.ts';\n\n// The same key as the core's, without importing the core.\nconst DEVTOOLS = Symbol.for('brumate.devtools');\n\n/** Something that happened on the page, for the log of the panel. */\nexport interface DevtoolsEntry {\n time: number;\n kind: 'handler' | 'part' | 'write' | 'call';\n text: string;\n /** The scope of a write, so the panel can mark it. */\n scope?: number;\n /** For a write: the component, the scope in the compiled component, and the slot. */\n write?: { component: string; k: number; slot: number };\n}\n\nexport interface DevtoolsState {\n scopes?: Map<number, Scope>;\n /** Writes a slot, as a handler does, so the page updates. */\n set?: (scope: Scope, slot: number, value: unknown) => void;\n log: DevtoolsEntry[];\n /** The scopes written since the panel last drew, by scope ID. */\n written: Set<number>;\n /** The URL prefix of the inspect endpoint of the dev server. */\n endpoint: string;\n /** Called after each change, while the panel is open. */\n changed?: () => void;\n}\n\nconst MAX_LOG = 300;\n\n/** The root scope of a scope, whose `m` names its component. */\nexport function rootOf(scope: Scope): Scope {\n let root = scope;\n while (root.p) {\n root = root.p;\n }\n return root;\n}\n\n/** A short text for a value in the log. */\nexport function preview(value: unknown): string {\n if (typeof value === 'string') {\n return JSON.stringify(value.length > 40 ? `${value.slice(0, 40)}…` : value);\n }\n if (typeof value === 'function') {\n return 'function';\n }\n if (Array.isArray(value)) {\n return `Array(${value.length})`;\n }\n if (value instanceof Element) {\n return `<${value.tagName.toLowerCase()}>`;\n }\n if (value !== null && typeof value === 'object') {\n const name = value.constructor?.name;\n return name && name !== 'Object' ? name : `{${Object.keys(value).slice(0, 3).join(', ')}}`;\n }\n return String(value);\n}\n\n/** Listens to the core, and adds the button that opens the panel. */\nexport function installDevtools(endpoint = '/__brumate/inspect', rpc = '/_brumate'): DevtoolsState {\n const state: DevtoolsState = { log: [], written: new Set(), endpoint };\n const add = (entry: Omit<DevtoolsEntry, 'time'>): void => {\n state.log.push({ ...entry, time: performance.now() });\n if (state.log.length > MAX_LOG) {\n state.log.splice(0, state.log.length - MAX_LOG);\n }\n state.changed?.();\n };\n const hooks: DevtoolsHooks = {\n attach(core) {\n state.scopes = core.scopes;\n state.set = core.set;\n state.changed?.();\n },\n handler(ref, element, event) {\n add({\n kind: 'handler',\n text: `${event?.type ?? 'call'} on <${element.tagName.toLowerCase()}>: ${ref}`,\n });\n },\n part(component, name) {\n add({ kind: 'part', text: `loaded ${component} ${name}` });\n },\n write(scope, slot, value) {\n state.written.add(scope.id);\n const root = rootOf(scope);\n add({\n kind: 'write',\n text: `scope ${scope.id} slot ${slot} = ${preview(value)}`,\n scope: scope.id,\n write: { component: root.m ?? '', k: scope.k, slot },\n });\n },\n };\n (globalThis as Record<symbol, DevtoolsHooks | undefined>)[DEVTOOLS] = hooks;\n\n // Server function calls, with how long each took and how it answered.\n const original = globalThis.fetch.bind(globalThis);\n globalThis.fetch = async (input, init) => {\n const url = new URL(input instanceof Request ? input.url : String(input), location.href);\n if (url.origin !== location.origin || !url.pathname.startsWith(`${rpc}/`)) {\n return original(input, init);\n }\n const name = decodeURIComponent(url.pathname.slice(rpc.length + 1));\n const started = performance.now();\n try {\n const response = await original(input, init);\n const took = Math.round(performance.now() - started);\n const redirect = response.headers.get('x-brumate-redirect');\n add({\n kind: 'call',\n text: `${name}: ${redirect ? `redirect to ${redirect}` : response.status} in ${took} ms`,\n });\n return response;\n } catch (error) {\n add({\n kind: 'call',\n text: `${name}: failed, ${error instanceof Error ? error.message : String(error)}`,\n });\n throw error;\n }\n };\n\n const host = document.createElement('brumate-devtools');\n const root = host.attachShadow({ mode: 'open' });\n const button = document.createElement('button');\n button.textContent = 'brm';\n button.title = 'Open the brumate devtools';\n button.setAttribute(\n 'style',\n 'position:fixed;right:12px;bottom:12px;z-index:2147483647;font:600 12px ui-monospace,monospace;padding:6px 10px;border-radius:999px;border:1px solid #8884;background:#111;color:#fff;cursor:pointer',\n );\n button.addEventListener('click', () => {\n void import('./devtools-panel.ts').then(({ togglePanel }) => togglePanel(root, state));\n });\n root.append(button);\n const append = (): void => {\n // Navigation replaces the body, so the button goes on the document element.\n document.documentElement.append(host);\n };\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', append);\n } else {\n append();\n }\n return state;\n}\n"],"mappings":";AAOA,MAAM,WAAW,OAAO,IAAI,kBAAkB;AA0B9C,MAAM,UAAU;;AAGhB,SAAgB,OAAO,OAAqB;CAC1C,IAAI,OAAO;CACX,OAAO,KAAK,GACV,OAAO,KAAK;CAEd,OAAO;AACT;;AAGA,SAAgB,QAAQ,OAAwB;CAC9C,IAAI,OAAO,UAAU,UACnB,OAAO,KAAK,UAAU,MAAM,SAAS,KAAK,GAAG,MAAM,MAAM,GAAG,EAAE,EAAE,KAAK,KAAK;CAE5E,IAAI,OAAO,UAAU,YACnB,OAAO;CAET,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,SAAS,MAAM,OAAO;CAE/B,IAAI,iBAAiB,SACnB,OAAO,IAAI,MAAM,QAAQ,YAAY,EAAE;CAEzC,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU;EAC/C,MAAM,OAAO,MAAM,aAAa;EAChC,OAAO,QAAQ,SAAS,WAAW,OAAO,IAAI,OAAO,KAAK,KAAK,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,KAAK,IAAI,EAAE;CAC1F;CACA,OAAO,OAAO,KAAK;AACrB;;AAGA,SAAgB,gBAAgB,WAAW,sBAAsB,MAAM,aAA4B;CACjG,MAAM,QAAuB;EAAE,KAAK,CAAC;EAAG,yBAAS,IAAI,IAAI;EAAG;CAAS;CACrE,MAAM,OAAO,UAA6C;EACxD,MAAM,IAAI,KAAK;GAAE,GAAG;GAAO,MAAM,YAAY,IAAI;EAAE,CAAC;EACpD,IAAI,MAAM,IAAI,SAAS,SACrB,MAAM,IAAI,OAAO,G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1D,IAAI;IACF,MAAM;IACN,MAAM,GAAG,KAAK,IAAI,WAAW,eAAe,aAAa,SAAS,OAAO,MAAM,KAAK;GACtF,CAAC;GACD,OAAO;EACT,SAAS,OAAO;GACd,IAAI;IACF,MAAM;IACN,MAAM,GAAG,KAAK,YAAY,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;GACjF,CAAC;GACD,MAAM;EACR;CACF;CAEA,MAAM,OAAO,SAAS,cAAc,kBAAkB;CACtD,MAAM,OAAO,KAAK,aAAa,EAAE,MAAM,OAAO,CAAC;CAC/C,MAAM,SAAS,SAAS,cAAc,QAAQ;CAC9C,OAAO,cAAc;CACrB,OAAO,QAAQ;CACf,OAAO,aACL,SACA,qMACF;CACA,OAAO,iBAAiB,eAAe;EACrC,OAAY,+BAAsB,CAAC,MAAM,EAAE,kBAAkB,YAAY,MAAM,KAAK,CAAC;CACvF,CAAC;CACD,KAAK,OAAO,MAAM;CAClB,MAAM,eAAqB;EAEzB,SAAS,gBAAgB,OAAO,IAAI;CACtC;CACA,IAAI,SAAS,eAAe,WAC1B,SAAS,iBAAiB,oBAAoB,MAAM;MAEpD,OAAO;CAET,OAAO;AACT"}
@@ -1,4 +1,4 @@
1
- import { n as preview } from "./devtools-Bm8cS7hX.js";
1
+ import { n as preview, r as rootOf } from "./devtools-BKjnHrnv.js";
2
2
  //#region src/runtime/devtools-panel.ts
3
3
  const STYLE = `
4
4
  :host { all: initial; }
@@ -76,12 +76,6 @@ function svg(tag, attributes, ...children) {
76
76
  node.append(...children);
77
77
  return node;
78
78
  }
79
- /** The root scope of a scope, whose `m` names its component. */
80
- function rootOf(scope) {
81
- let root = scope;
82
- while (root.p) root = root.p;
83
- return root;
84
- }
85
79
  /** A value that can be edited as text: what JSON can hold. */
86
80
  function editable(value) {
87
81
  if (value === null || [
@@ -163,7 +157,7 @@ function togglePanel(root, state) {
163
157
  const outline = (scope) => {
164
158
  for (const box of outlines.splice(0)) box.remove();
165
159
  if (scope === void 0) return;
166
- for (const target of document.querySelectorAll(`[data-b^="${scope}:"]`)) {
160
+ for (const target of document.querySelectorAll(`[b-b^="${scope}:"]`)) {
167
161
  const rect = target.getBoundingClientRect();
168
162
  const box = element("div", {
169
163
  class: "outline",
@@ -174,12 +168,12 @@ function togglePanel(root, state) {
174
168
  }
175
169
  };
176
170
  const onPick = (event) => {
177
- const target = event.target?.closest?.("[data-b]");
171
+ const target = event.target?.closest?.("[b-b]");
178
172
  if (!target || event.composedPath().includes(panel)) return;
179
173
  event.preventDefault();
180
174
  event.stopImmediatePropagation();
181
175
  stopPicking();
182
- selectedScope = Number(target.getAttribute("data-b").split(":")[0]);
176
+ selectedScope = Number(target.getAttribute("b-b").split(":")[0]);
183
177
  const scope = state.scopes?.get(selectedScope);
184
178
  selected = scope ? rootOf(scope).m : selected;
185
179
  tab = "scopes";
@@ -205,7 +199,7 @@ function togglePanel(root, state) {
205
199
  const line = element("div", { class: "slot" }, element("span", { class: "name" }, name), " = ");
206
200
  if (editing?.scope === scope.id && editing.slot === slot) {
207
201
  const input = element("input", { "aria-label": `New value of ${name}` });
208
- input.value = typeof value === "string" ? JSON.stringify(value) : JSON.stringify(value) ?? "";
202
+ input.value = JSON.stringify(value) ?? "";
209
203
  input.addEventListener("keydown", (event) => {
210
204
  if (event.key === "Enter") {
211
205
  editing = void 0;
@@ -220,8 +214,9 @@ function togglePanel(root, state) {
220
214
  queueMicrotask(() => input.focus());
221
215
  return line;
222
216
  }
223
- const text = element("span", { class: editable(value) && state.set ? "value" : "" }, preview(value));
224
- if (editable(value) && state.set) {
217
+ const canEdit = editable(value) && state.set !== void 0;
218
+ const text = element("span", { class: canEdit ? "value" : "" }, preview(value));
219
+ if (canEdit) {
225
220
  text.title = "Click to edit. Enter JSON, or text for a string.";
226
221
  text.addEventListener("click", () => {
227
222
  editing = {
@@ -240,7 +235,7 @@ function togglePanel(root, state) {
240
235
  const classes = ["scope"];
241
236
  if (state.written.has(scope.id)) classes.push("written");
242
237
  if (selectedScope === scope.id) classes.push("selected");
243
- const label = element("div", { class: "scope-label" }, `scope ${scope.id}${plan ? ` · ${plan.label}` : ""}`);
238
+ const label = element("div", { class: "scope-label" }, `scope ${scope.id}${plan ? ` · ${plan.label}` : ""}${scope.h ? " · hidden" : ""}`);
244
239
  label.addEventListener("mouseenter", () => outline(scope.id));
245
240
  label.addEventListener("mouseleave", () => outline());
246
241
  const box = element("div", { class: classes.join(" ") }, label);
@@ -296,16 +291,12 @@ function togglePanel(root, state) {
296
291
  }
297
292
  const { nodes, edges } = info.graph;
298
293
  const instance = roots().find((scope) => scope.m === id);
299
- const scopeOfNode = (k) => {
300
- const visit = (scope) => {
301
- if (scope.k === k) return scope;
302
- for (const child of scope.children) {
303
- const found = child.m === void 0 ? visit(child) : void 0;
304
- if (found) return found;
305
- }
306
- };
307
- return instance && visit(instance);
294
+ const scopeOfNode = /* @__PURE__ */ new Map();
295
+ const visit = (scope) => {
296
+ if (!scopeOfNode.has(scope.k)) scopeOfNode.set(scope.k, scope);
297
+ for (const child of scope.children) if (child.m === void 0) visit(child);
308
298
  };
299
+ if (instance) visit(instance);
309
300
  const now = performance.now();
310
301
  const hot = /* @__PURE__ */ new Set();
311
302
  for (const entry of state.log) if (entry.write?.component === id && now - entry.time < HOT_MS) nodes.forEach((node, index) => {
@@ -319,7 +310,13 @@ function togglePanel(root, state) {
319
310
  }
320
311
  }
321
312
  const depth = nodes.map(() => 0);
322
- for (let round = 0; round < nodes.length; round++) for (const [from, to] of edges) depth[to] = Math.max(depth[to], depth[from] + 1);
313
+ for (let round = 0, changed = true; changed && round < nodes.length; round++) {
314
+ changed = false;
315
+ for (const [from, to] of edges) if (depth[from] + 1 > depth[to]) {
316
+ depth[to] = depth[from] + 1;
317
+ changed = true;
318
+ }
319
+ }
323
320
  const rows = /* @__PURE__ */ new Map();
324
321
  const position = nodes.map((_, index) => {
325
322
  const column = depth[index];
@@ -353,7 +350,7 @@ function togglePanel(root, state) {
353
350
  x: x + 6,
354
351
  y: y + 16
355
352
  });
356
- const owner = node.slot === void 0 ? void 0 : scopeOfNode(node.scope);
353
+ const owner = node.slot === void 0 ? void 0 : scopeOfNode.get(node.scope);
357
354
  const value = owner && node.slot !== void 0 ? ` = ${preview(owner.s[node.slot])}` : "";
358
355
  text.textContent = `${node.label}${value}`.slice(0, 22);
359
356
  const title = svg("title", {});
@@ -434,4 +431,4 @@ function togglePanel(root, state) {
434
431
  //#endregion
435
432
  export { togglePanel };
436
433
 
437
- //# sourceMappingURL=devtools-panel-CTbDSBBA.js.map
434
+ //# sourceMappingURL=devtools-panel-AWOn0VK2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"devtools-panel-AWOn0VK2.js","names":[],"sources":["../src/runtime/devtools-panel.ts"],"sourcesContent":["// The panel of the devtools overlay. It reads the core through the hooks in\n// `devtools.ts`, and asks the dev server about each component.\n//\n// - Scopes: each component on the page, its scopes and the value of each\n// slot by name. A value can be edited, which writes it as a handler does.\n// Hovering a scope outlines its elements, and Pick finds the scope of an\n// element of the page.\n// - Graph: the values and markup of a component that change in the\n// browser, and what reads what. A write marks its node and the nodes after it.\n// - Log: handlers, loaded parts, writes and server function calls.\n// - Report: the inspect report of a component.\n\nimport type { Scope } from './client.ts';\nimport { preview, rootOf } from './devtools.ts';\nimport type { DevtoolsEntry, DevtoolsState } from './devtools.ts';\n\n/** What the dev server tells about a component: see the inspect endpoint of the plugin. */\ninterface ComponentInfo {\n name: string;\n file: string;\n /** Each scope of the component, by its number in the compiled component. */\n scopes: Record<number, { label: string; slots: string[] }>;\n graph?: {\n nodes: { kind: string; label: string; scope: number; slot?: number }[];\n /** Pairs of node indexes: the first is read by the second. */\n edges: [number, number][];\n };\n /** The inspect report as text. */\n text: string;\n}\n\nconst STYLE = `\n:host { all: initial; }\n.panel { position: fixed; right: 12px; bottom: 52px; z-index: 2147483647; width: min(520px, calc(100vw - 24px)); height: min(64vh, 620px); display: flex; flex-direction: column; background: #111; color: #eee; font: 12px/1.5 ui-monospace, monospace; border: 1px solid #8884; border-radius: 8px; box-shadow: 0 8px 32px #0006; overflow: hidden; }\n.bar { display: flex; gap: 4px; padding: 6px; border-bottom: 1px solid #8883; align-items: center; flex-wrap: wrap; }\nbutton, select { font: inherit; color: inherit; background: none; border: 1px solid transparent; border-radius: 4px; padding: 2px 8px; cursor: pointer; }\nselect { border-color: #8884; background: #111; }\n.bar .tab[aria-selected=\"true\"], .bar button[aria-pressed=\"true\"] { border-color: #8886; background: #fff1; }\n.bar .end { margin-left: auto; }\n.body { flex: 1; overflow: auto; padding: 8px; }\n.component { margin-bottom: 10px; }\n.component > button { font-weight: 600; color: #9cf; padding: 0; }\n.scope { margin-left: 12px; padding-left: 8px; border-left: 1px solid #8883; }\n.scope.selected { border-left-color: #9cf; background: #9cf1; }\n.scope-label { color: #aaa; cursor: default; }\n.slot { white-space: pre; }\n.slot .name { color: #fc9; }\n.slot .value { cursor: text; border-bottom: 1px dotted #8886; }\n.slot input { font: inherit; color: inherit; background: #000; border: 1px solid #9cf; border-radius: 3px; padding: 0 4px; width: 60%; }\n.written { animation: flash 0.8s; }\n@keyframes flash { from { background: #fd04; } to { background: transparent; } }\n.entry { white-space: pre-wrap; border-bottom: 1px solid #8882; padding: 2px 0; }\n.entry .time { color: #888; margin-right: 6px; }\n.entry.handler .kind { color: #9cf; }\n.entry.part .kind { color: #9e9; }\n.entry.write .kind { color: #fc9; }\n.entry.call .kind { color: #f9c; }\n.filters label { display: inline-flex; gap: 3px; align-items: center; margin-right: 6px; }\npre { margin: 0; white-space: pre-wrap; }\n.empty { color: #888; }\nsvg text { fill: #eee; font: 11px ui-monospace, monospace; }\nsvg rect { fill: #222; stroke: #8886; }\nsvg .kind-signal rect, svg .kind-prop rect { stroke: #9cf; }\nsvg .kind-memo rect { stroke: #c9f; }\nsvg .kind-effect rect { stroke: #9e9; }\nsvg .hot rect { fill: #fd03; stroke: #fd0; }\n.legend { color: #aaa; margin: 6px 0; }\n.legend b { font-weight: normal; }\n.legend .signal { color: #9cf; } .legend .memo { color: #c9f; } .legend .effect { color: #9e9; } .legend .hot { color: #fd0; }\nsvg line { stroke: #8886; }\nsvg .hot-edge { stroke: #fd0; }\n.outline { position: fixed; pointer-events: none; border: 2px solid #9cf; background: #9cf2; border-radius: 3px; z-index: 2147483646; }\n`;\n\ntype Tab = 'scopes' | 'graph' | 'log' | 'report';\nconst KINDS: DevtoolsEntry['kind'][] = ['handler', 'part', 'write', 'call'];\n/** How long a write marks the nodes of the graph. */\nconst HOT_MS = 1500;\n\nconst components = new Map<string, Promise<ComponentInfo | undefined>>();\nconst known = new Map<string, ComponentInfo>();\n\n/** Asks the dev server about a component, once. */\nfunction componentInfo(state: DevtoolsState, id: string): Promise<ComponentInfo | undefined> {\n let info = components.get(id);\n if (!info) {\n info = fetch(`${state.endpoint}/${encodeURIComponent(id)}`)\n .then((response) => (response.ok ? (response.json() as Promise<ComponentInfo>) : undefined))\n .then((value) => {\n if (value) {\n known.set(id, value);\n }\n return value;\n })\n .catch(() => undefined);\n components.set(id, info);\n }\n return info;\n}\n\nfunction element<K extends keyof HTMLElementTagNameMap>(\n tag: K,\n attributes: Record<string, string> = {},\n ...children: (Node | string)[]\n): HTMLElementTagNameMap[K] {\n const node = document.createElement(tag);\n for (const [name, value] of Object.entries(attributes)) {\n node.setAttribute(name, value);\n }\n node.append(...children);\n return node;\n}\n\nfunction svg(\n tag: string,\n attributes: Record<string, string | number>,\n ...children: Node[]\n): SVGElement {\n const node = document.createElementNS('http://www.w3.org/2000/svg', tag);\n for (const [name, value] of Object.entries(attributes)) {\n node.setAttribute(name, String(value));\n }\n node.append(...children);\n return node;\n}\n\n/** A value that can be edited as text: what JSON can hold. */\nfunction editable(value: unknown): boolean {\n if (value === null || ['string', 'number', 'boolean'].includes(typeof value)) {\n return true;\n }\n if (typeof value !== 'object' || value instanceof Element) {\n return false;\n }\n try {\n JSON.stringify(value);\n return true;\n } catch {\n return false;\n }\n}\n\n/** Reads what a person typed: JSON, or else the text as a string. */\nfunction parseValue(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\n/** A write with the name of its slot, once the dev server has said what it is. */\nfunction describe(entry: DevtoolsEntry): string {\n const write = entry.write;\n const info = write && known.get(write.component);\n const name = info?.scopes[write!.k]?.slots[write!.slot];\n return name\n ? `${info!.name} ${name} = ${entry.text.split(' = ').slice(1).join(' = ')}`\n : entry.text;\n}\n\nlet panel: HTMLElement | undefined;\n\n/** Opens the panel, or closes it when it is open. */\nexport function togglePanel(root: ShadowRoot, state: DevtoolsState): void {\n if (panel) {\n panel.remove();\n panel = undefined;\n state.changed = undefined;\n return;\n }\n let tab: Tab = 'scopes';\n let selected: string | undefined;\n let selectedScope: number | undefined;\n let editing: { scope: number; slot: number } | undefined;\n let paused = false;\n const shown = new Set<DevtoolsEntry['kind']>(KINDS);\n // The log as it was when Pause was pressed.\n let frozen: DevtoolsEntry[] | undefined;\n\n const body = element('div', { class: 'body' });\n const bar = element('div', { class: 'bar', role: 'tablist' });\n for (const [name, label] of [\n ['scopes', 'Scopes'],\n ['graph', 'Graph'],\n ['log', 'Log'],\n ['report', 'Report'],\n ] as const) {\n const button = element('button', { class: 'tab', role: 'tab', 'data-tab': name }, label);\n button.addEventListener('click', () => {\n tab = name;\n draw();\n });\n bar.append(button);\n }\n const pick = element(\n 'button',\n {\n class: 'end',\n 'aria-pressed': 'false',\n title: 'Click an element of the page to find its scope',\n },\n 'Pick',\n );\n bar.append(pick);\n panel = element('div', { class: 'panel' }, element('style', {}, STYLE), bar, body);\n root.append(panel);\n // Without an event, the core has not loaded yet, and nothing knows the components of the page.\n if (!state.scopes) {\n document.dispatchEvent(new Event('brumate:core'));\n }\n\n // Outlines the elements of a scope on the page.\n const outlines: HTMLElement[] = [];\n const outline = (scope?: number): void => {\n for (const box of outlines.splice(0)) {\n box.remove();\n }\n if (scope === undefined) {\n return;\n }\n for (const target of document.querySelectorAll(`[b-b^=\"${scope}:\"]`)) {\n const rect = target.getBoundingClientRect();\n const box = element('div', {\n class: 'outline',\n style: `left:${rect.left}px;top:${rect.top}px;width:${rect.width}px;height:${rect.height}px`,\n });\n root.append(box);\n outlines.push(box);\n }\n };\n\n // Pick: the next click on the page selects the scope of its element.\n const onPick = (event: MouseEvent): void => {\n const target = (event.target as Element | null)?.closest?.('[b-b]');\n if (!target || event.composedPath().includes(panel!)) {\n return;\n }\n event.preventDefault();\n event.stopImmediatePropagation();\n stopPicking();\n selectedScope = Number(target.getAttribute('b-b')!.split(':')[0]);\n const scope = state.scopes?.get(selectedScope);\n selected = scope ? rootOf(scope).m : selected;\n tab = 'scopes';\n draw();\n };\n const stopPicking = (): void => {\n pick.setAttribute('aria-pressed', 'false');\n window.removeEventListener('click', onPick, true);\n document.documentElement.style.cursor = '';\n };\n pick.addEventListener('click', () => {\n if (pick.getAttribute('aria-pressed') === 'true') {\n stopPicking();\n return;\n }\n pick.setAttribute('aria-pressed', 'true');\n document.documentElement.style.cursor = 'crosshair';\n // On the window, so it runs before the listeners of the loader on the document.\n window.addEventListener('click', onPick, true);\n });\n\n /** A slot with its name and value. A value that JSON can hold can be edited. */\n const drawSlot = (scope: Scope, slot: number, name: string): HTMLElement => {\n const value = scope.s[slot];\n const line = element('div', { class: 'slot' }, element('span', { class: 'name' }, name), ' = ');\n if (editing?.scope === scope.id && editing.slot === slot) {\n const input = element('input', { 'aria-label': `New value of ${name}` });\n input.value = JSON.stringify(value) ?? '';\n input.addEventListener('keydown', (event) => {\n if (event.key === 'Enter') {\n editing = undefined;\n state.set?.(scope, slot, parseValue(input.value));\n draw();\n } else if (event.key === 'Escape') {\n editing = undefined;\n draw();\n }\n });\n line.append(input);\n queueMicrotask(() => input.focus());\n return line;\n }\n const canEdit = editable(value) && state.set !== undefined;\n const text = element('span', { class: canEdit ? 'value' : '' }, preview(value));\n if (canEdit) {\n text.title = 'Click to edit. Enter JSON, or text for a string.';\n text.addEventListener('click', () => {\n editing = { scope: scope.id, slot };\n draw();\n });\n }\n line.append(text);\n return line;\n };\n\n /** A scope with its slots and the scopes inside it, other than components. */\n const drawScope = (scope: Scope, info: ComponentInfo | undefined): HTMLElement => {\n const plan = info?.scopes[scope.k];\n const classes = ['scope'];\n if (state.written.has(scope.id)) {\n classes.push('written');\n }\n if (selectedScope === scope.id) {\n classes.push('selected');\n }\n const label = element(\n 'div',\n { class: 'scope-label' },\n // A hidden `#offscreen` body keeps its scope and its slots.\n `scope ${scope.id}${plan ? ` · ${plan.label}` : ''}${scope.h ? ' · hidden' : ''}`,\n );\n label.addEventListener('mouseenter', () => outline(scope.id));\n label.addEventListener('mouseleave', () => outline());\n const box = element('div', { class: classes.join(' ') }, label);\n scope.s.forEach((_, slot) =>\n box.append(drawSlot(scope, slot, plan?.slots[slot] ?? `slot ${slot}`)),\n );\n for (const child of scope.children) {\n if (child.m === undefined) {\n box.append(drawScope(child, info));\n }\n }\n return box;\n };\n\n const roots = (): Scope[] =>\n [...(state.scopes?.values() ?? [])].filter((scope) => scope.m !== undefined);\n\n const drawScopes = async (): Promise<void> => {\n const list = roots();\n const infos = await Promise.all(list.map((scope) => componentInfo(state, scope.m!)));\n const content = element('div');\n list.forEach((scope, index) => {\n const info = infos[index];\n const name = element('button', {}, info ? `${info.name} (${info.file})` : scope.m!);\n name.title = 'Show the graph of this component';\n name.addEventListener('click', () => {\n selected = scope.m;\n tab = 'graph';\n draw();\n });\n content.append(element('div', { class: 'component' }, name, drawScope(scope, info)));\n });\n if (list.length === 0) {\n content.append(\n element('div', { class: 'empty' }, 'No scopes yet. The first event loads them.'),\n );\n }\n body.replaceChildren(content);\n body.querySelector('.selected')?.scrollIntoView({ block: 'nearest' });\n };\n\n /** A select of the components on the page, for Graph and Report. */\n const chooser = (current: string | undefined): HTMLElement => {\n const select = element('select', { 'aria-label': 'Component' });\n for (const id of new Set(roots().map((scope) => scope.m!))) {\n const option = element('option', { value: id }, known.get(id)?.name ?? id);\n option.selected = id === current;\n select.append(option);\n }\n select.addEventListener('change', () => {\n selected = select.value;\n draw();\n });\n return element('div', {}, select);\n };\n\n let cooling: ReturnType<typeof setTimeout> | undefined;\n\n const drawGraph = async (): Promise<void> => {\n const id = selected ?? roots()[0]?.m;\n const info = id ? await componentInfo(state, id) : undefined;\n if (!id || !info) {\n body.replaceChildren(element('div', { class: 'empty' }, 'No component yet.'));\n return;\n }\n if (!info.graph) {\n body.replaceChildren(\n chooser(id),\n element(\n 'div',\n { class: 'empty' },\n 'The dev server sent no graph. It runs an older brumate than this panel: restart it.',\n ),\n );\n return;\n }\n const { nodes, edges } = info.graph;\n // The current value of each value node, from the first instance of the component.\n const instance = roots().find((scope) => scope.m === id);\n // The first scope of the instance for each scope in the compiled component.\n const scopeOfNode = new Map<number, Scope>();\n const visit = (scope: Scope): void => {\n if (!scopeOfNode.has(scope.k)) {\n scopeOfNode.set(scope.k, scope);\n }\n for (const child of scope.children) {\n if (child.m === undefined) {\n visit(child);\n }\n }\n };\n if (instance) {\n visit(instance);\n }\n // Nodes that a recent write reached: the written value, and what reads it.\n const now = performance.now();\n const hot = new Set<number>();\n for (const entry of state.log) {\n if (entry.write?.component === id && now - entry.time < HOT_MS) {\n nodes.forEach((node, index) => {\n if (node.scope === entry.write!.k && node.slot === entry.write!.slot) {\n hot.add(index);\n }\n });\n }\n }\n for (let grew = true; grew;) {\n grew = false;\n for (const [from, to] of edges) {\n if (hot.has(from) && !hot.has(to)) {\n hot.add(to);\n grew = true;\n }\n }\n }\n // Columns by the longest path from a value that nothing feeds.\n const depth = nodes.map(() => 0);\n for (let round = 0, changed = true; changed && round < nodes.length; round++) {\n changed = false;\n for (const [from, to] of edges) {\n if (depth[from]! + 1 > depth[to]!) {\n depth[to] = depth[from]! + 1;\n changed = true;\n }\n }\n }\n const rows = new Map<number, number>();\n const position = nodes.map((_, index) => {\n const column = depth[index]!;\n const row = rows.get(column) ?? 0;\n rows.set(column, row + 1);\n return { x: 8 + column * 150, y: 8 + row * 34 };\n });\n const width = 8 + (Math.max(0, ...depth) + 1) * 150;\n const height = 8 + Math.max(1, ...rows.values()) * 34;\n const graph = svg('svg', { width, height, role: 'img', 'aria-label': `Graph of ${info.name}` });\n for (const [from, to] of edges) {\n const a = position[from]!;\n const b = position[to]!;\n graph.append(\n svg('line', {\n x1: a.x + 132,\n y1: a.y + 12,\n x2: b.x,\n y2: b.y + 12,\n class: hot.has(from) && hot.has(to) ? 'hot-edge' : '',\n }),\n );\n }\n nodes.forEach((node, index) => {\n const { x, y } = position[index]!;\n const text = svg('text', { x: x + 6, y: y + 16 });\n const owner = node.slot === undefined ? undefined : scopeOfNode.get(node.scope);\n const value = owner && node.slot !== undefined ? ` = ${preview(owner.s[node.slot])}` : '';\n text.textContent = `${node.label}${value}`.slice(0, 22);\n const title = svg('title', {});\n title.textContent = `${node.kind} ${node.label}${value}`;\n graph.append(\n svg(\n 'g',\n { class: `kind-${node.kind}${hot.has(index) ? ' hot' : ''}` },\n svg('rect', { x, y, width: 132, height: 24, rx: 4 }),\n text,\n title,\n ),\n );\n });\n const legend = element(\n 'div',\n { class: 'legend' },\n 'What reads what, left to right: ',\n element('b', { class: 'signal' }, 'signals and props'),\n ', ',\n element('b', { class: 'memo' }, 'memos'),\n ', markup and ',\n element('b', { class: 'effect' }, 'effects'),\n '. A change lights up in ',\n element('b', { class: 'hot' }, 'yellow'),\n ' what it reaches.',\n );\n body.replaceChildren(\n chooser(id),\n ...(nodes.length > 0\n ? [legend, graph]\n : [\n element('div', { class: 'empty' }, 'Nothing in this component changes in the browser.'),\n ]),\n );\n // Draws again when the marks of the last write expire.\n if (hot.size > 0) {\n clearTimeout(cooling);\n cooling = setTimeout(() => state.changed?.(), HOT_MS);\n }\n };\n\n const drawLog = (): void => {\n const filters = element('div', { class: 'filters' });\n for (const kind of KINDS) {\n const box = element('input', { type: 'checkbox' });\n box.checked = shown.has(kind);\n box.addEventListener('change', () => {\n if (box.checked) {\n shown.add(kind);\n } else {\n shown.delete(kind);\n }\n draw();\n });\n filters.append(element('label', {}, box, kind));\n }\n const pause = element(\n 'button',\n { 'aria-pressed': String(paused) },\n paused ? 'Resume' : 'Pause',\n );\n pause.addEventListener('click', () => {\n paused = !paused;\n frozen = paused ? [...state.log] : undefined;\n draw();\n });\n const clear = element('button', {}, 'Clear');\n clear.addEventListener('click', () => {\n state.log.length = 0;\n frozen = paused ? [] : undefined;\n draw();\n });\n filters.append(pause, clear);\n const list = element('div');\n const entries = (frozen ?? state.log).filter((entry) => shown.has(entry.kind));\n for (const entry of entries.toReversed()) {\n list.append(\n element(\n 'div',\n { class: `entry ${entry.kind}` },\n element('span', { class: 'time' }, `${(entry.time / 1000).toFixed(2)}s`),\n element('span', { class: 'kind' }, entry.kind),\n ` ${entry.kind === 'write' ? describe(entry) : entry.text}`,\n ),\n );\n }\n if (entries.length === 0) {\n list.append(element('div', { class: 'empty' }, 'Nothing to show.'));\n }\n body.replaceChildren(filters, list);\n };\n\n const drawReport = async (): Promise<void> => {\n const id = selected ?? roots()[0]?.m;\n const info = id ? await componentInfo(state, id) : undefined;\n body.replaceChildren(\n ...(info\n ? [chooser(id), element('pre', {}, info.text)]\n : [element('div', { class: 'empty' }, 'No component yet.')]),\n );\n };\n\n let queued = false;\n const draw = (): void => {\n for (const button of bar.querySelectorAll('.tab')) {\n button.setAttribute('aria-selected', String((button as HTMLElement).dataset.tab === tab));\n }\n if (tab === 'log') {\n drawLog();\n return;\n }\n const drawn = tab === 'scopes' ? drawScopes() : tab === 'graph' ? drawGraph() : drawReport();\n // Marks of writes show once, on the next draw of the scopes.\n void drawn.then(() => {\n if (tab === 'scopes') {\n state.written.clear();\n }\n });\n };\n // Changes come in bursts, so the panel draws once per frame. It waits while a value is edited.\n state.changed = () => {\n if (!queued && !editing && !(paused && tab === 'log')) {\n queued = true;\n requestAnimationFrame(() => {\n queued = false;\n if (panel) {\n draw();\n }\n });\n }\n };\n draw();\n}\n"],"mappings":";;AA+BA,MAAM,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4Cd,MAAM,QAAiC;CAAC;CAAW;CAAQ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UAAU,QAAQ,QAAQ;GACrD,SAAS;GACT,4BAA4B;IAC1B,SAAS;IACT,IAAI,OACF,KAAK;GAET,CAAC;EACH;CACF;CACA,KAAK;AACP"}
@@ -1,4 +1,4 @@
1
- import { h as functionId } from "./inspect-CGCWfaEx.js";
1
+ import { g as functionId } from "./inspect-BPchdWbU.js";
2
2
  import { parseSync } from "oxc-parser";
3
3
  import { readFile, readdir } from "node:fs/promises";
4
4
  import path from "node:path";
@@ -152,7 +152,26 @@ async function findServerFiles(root, exclude) {
152
152
  await visit(root);
153
153
  return result.toSorted();
154
154
  }
155
+ /**
156
+ * Finds every script under a directory, such as `.ts` and `.brm.ts` files, as
157
+ * absolute paths with forward slashes, without reading them.
158
+ */
159
+ async function findScripts(root, exclude) {
160
+ const result = [];
161
+ const visit = async (directory) => {
162
+ const directories = [];
163
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
164
+ const file = path.join(directory, entry.name);
165
+ if (entry.isDirectory()) {
166
+ if (!exclude(entry.name)) directories.push(visit(file));
167
+ } else if (/\.[cm]?[jt]sx?$/.test(entry.name) && !entry.name.endsWith(".d.ts")) result.push(file.split(path.sep).join("/"));
168
+ }
169
+ await Promise.all(directories);
170
+ };
171
+ await visit(root);
172
+ return result.toSorted();
173
+ }
155
174
  //#endregion
156
- export { isScriptFile as a, serverStubs as c, hasUseServer as i, findFiles as n, serverExports as o, findServerFiles as r, serverModule as s, defaultExclude as t };
175
+ export { hasUseServer as a, serverModule as c, findServerFiles as i, serverStubs as l, findFiles as n, isScriptFile as o, findScripts as r, serverExports as s, defaultExclude as t };
157
176
 
158
- //# sourceMappingURL=files-D_JUcSU5.js.map
177
+ //# sourceMappingURL=files-DdT84mPy.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"files-D_JUcSU5.js","names":[],"sources":["../src/server-files.ts","../src/files.ts"],"sourcesContent":["// Files of server functions. A `.ts` or `.js` file whose first statement is\n// `'use server'` holds functions that only run on the server. Its exports are\n// server functions: the browser gets a stub for each one, which calls the\n// server, and the code of the file never ships.\n\nimport { parseSync } from 'oxc-parser';\nimport { functionId } from './plan.ts';\n\n/** The import of the stubs, which call server functions with `rpc` of the core. */\nconst CLIENT = 'brumate/client';\n\n/** True for a file whose first statement is `'use server'`, after comments. */\nexport function hasUseServer(source: string): boolean {\n return /^(?:\\s|\\/\\/[^\\n]*\\n|\\/\\*[\\s\\S]*?\\*\\/)*(['\"])use server\\1/.test(source);\n}\n\n/** True for a path that can be a file of server functions. */\nexport function isScriptFile(path: string): boolean {\n return (\n /\\.[cm]?[jt]sx?$/.test(path) && !path.endsWith('.d.ts') && !/\\.brm\\.[cm]?[jt]s$/.test(path)\n );\n}\n\n/** True for a function expression or an arrow. */\nfunction isFunction(node: { type: string } | null | undefined): boolean {\n return node?.type === 'ArrowFunctionExpression' || node?.type === 'FunctionExpression';\n}\n\n/**\n * The names of the functions that a file of server functions exports.\n * Throws for an export that is not a function, because the browser can only\n * call a server function through its stub.\n */\nexport function serverExports(source: string, filename: string): string[] {\n const { program, errors } = parseSync(filename, source, { lang: 'ts' });\n if (errors[0]) {\n throw new Error(`${errors[0].message} (${filename})`);\n }\n const functions = new Set<string>();\n const values = new Set<string>();\n const local = new Map<string, 'function' | 'value'>();\n for (const statement of program.body) {\n const declaration =\n statement.type === 'ExportNamedDeclaration' ? statement.declaration : statement;\n if (declaration?.type === 'FunctionDeclaration' && declaration.id) {\n local.set(declaration.id.name, 'function');\n } else if (declaration?.type === 'VariableDeclaration') {\n for (const declarator of declaration.declarations) {\n if (declarator.id.type === 'Identifier') {\n local.set(declarator.id.name, isFunction(declarator.init) ? 'function' : 'value');\n }\n }\n }\n }\n for (const statement of program.body) {\n if (statement.type === 'ExportDefaultDeclaration') {\n const value = statement.declaration;\n if (value.type === 'FunctionDeclaration' || isFunction(value)) {\n functions.add('default');\n } else {\n values.add('default');\n }\n } else if (statement.type === 'ExportNamedDeclaration') {\n if (statement.exportKind === 'type') {\n continue;\n }\n const declaration = statement.declaration;\n if (declaration?.type === 'FunctionDeclaration' && declaration.id) {\n functions.add(declaration.id.name);\n } else if (declaration?.type === 'VariableDeclaration') {\n for (const declarator of declaration.declarations) {\n if (declarator.id.type === 'Identifier') {\n (isFunction(declarator.init) ? functions : values).add(declarator.id.name);\n }\n }\n } else if (declaration && !declaration.type.startsWith('TS')) {\n values.add('a class');\n }\n for (const specifier of statement.specifiers) {\n if (specifier.exportKind === 'type') {\n continue;\n }\n const name =\n specifier.exported.type === 'Identifier'\n ? specifier.exported.name\n : specifier.exported.value;\n const from = specifier.local.type === 'Identifier' ? specifier.local.name : '';\n (local.get(from) === 'function' && !statement.source ? functions : values).add(name);\n }\n } else if (statement.type === 'ExportAllDeclaration') {\n values.add('*');\n }\n }\n if (values.size > 0) {\n throw new Error(\n `A 'use server' file exports only functions, because the browser calls them on the server. ${[...values].join(', ')} of ${filename} is not one`,\n );\n }\n return [...functions];\n}\n\n/** The module that the browser gets in place of a file of server functions. */\nexport function serverStubs(\n source: string,\n filename: string,\n id: string,\n hideNames = false,\n): string {\n const lines = [`import { rpc } from ${JSON.stringify(CLIENT)};`];\n for (const name of serverExports(source, filename)) {\n const call = `(...args) => rpc(${JSON.stringify(functionId(id, name, hideNames))}, args)`;\n lines.push(name === 'default' ? `export default ${call};` : `export const ${name} = ${call};`);\n }\n return `${lines.join('\\n')}\\n`;\n}\n\n/**\n * The module that the server runs for a file of server functions: the file,\n * with each exported function wrapped, so its calls while a page renders\n * share a result when their arguments are the same. Offsets stay the same.\n */\nexport function serverModule(source: string, filename: string, id: string): string {\n const { program } = parseSync(filename, source, { lang: 'ts' });\n // Local names of exported functions, with the name that each is exported as.\n const wrapped = new Map<string, string>();\n const declarations = new Map<string, 'function' | 'const'>();\n let code = source;\n for (const statement of program.body) {\n const declaration =\n statement.type === 'ExportNamedDeclaration' ? statement.declaration : statement;\n if (declaration?.type === 'FunctionDeclaration' && declaration.id) {\n declarations.set(declaration.id.name, 'function');\n } else if (declaration?.type === 'VariableDeclaration') {\n for (const declarator of declaration.declarations) {\n if (declarator.id.type === 'Identifier' && isFunction(declarator.init)) {\n declarations.set(declarator.id.name, 'const');\n }\n }\n }\n }\n const letOf = (declaration: { start: number; kind: string }): void => {\n // `const` becomes `let `, so the function can be wrapped and offsets stay the same.\n if (declaration.kind === 'const') {\n code = `${code.slice(0, declaration.start)}let ${code.slice(declaration.start + 5)}`;\n }\n };\n for (const statement of program.body) {\n if (\n statement.type !== 'ExportNamedDeclaration' ||\n statement.source ||\n statement.exportKind === 'type'\n ) {\n continue;\n }\n const declaration = statement.declaration;\n if (declaration?.type === 'FunctionDeclaration' && declaration.id) {\n wrapped.set(declaration.id.name, declaration.id.name);\n } else if (declaration?.type === 'VariableDeclaration') {\n for (const declarator of declaration.declarations) {\n if (declarator.id.type === 'Identifier' && isFunction(declarator.init)) {\n wrapped.set(declarator.id.name, declarator.id.name);\n letOf(declaration);\n }\n }\n }\n for (const specifier of statement.specifiers) {\n const local = specifier.local.type === 'Identifier' ? specifier.local.name : '';\n const exported =\n specifier.exported.type === 'Identifier'\n ? specifier.exported.name\n : specifier.exported.value;\n if (declarations.has(local)) {\n wrapped.set(local, exported);\n }\n }\n }\n // A `const` arrow that `export { name }` exports is declared with `let` too.\n for (const statement of program.body) {\n if (statement.type === 'VariableDeclaration') {\n for (const declarator of statement.declarations) {\n if (declarator.id.type === 'Identifier' && wrapped.has(declarator.id.name)) {\n letOf(statement);\n }\n }\n }\n }\n if (wrapped.size === 0) {\n return source;\n }\n const lines = [\"import { dedupe as __brumateDedupe } from 'brumate/server';\"];\n for (const [local, exported] of wrapped) {\n lines.push(`${local} = __brumateDedupe(${local}, ${JSON.stringify(`${id}#${exported}`)});`);\n }\n return `${code}\\n${lines.join('\\n')}\\n`;\n}\n","import { readFile, readdir } from 'node:fs/promises';\nimport path from 'node:path';\nimport { hasUseServer, isScriptFile } from './server-files.ts';\n\n/** Skips `node_modules`, `dist` and hidden directories when looking for `.brm` files. */\nexport function defaultExclude(directory: string): boolean {\n return directory === 'node_modules' || directory === 'dist' || directory.startsWith('.');\n}\n\n/** Finds every `.brm` file under a directory, as absolute paths with forward slashes. */\nexport async function findFiles(\n root: string,\n exclude: (directory: string) => boolean,\n): Promise<string[]> {\n const result: string[] = [];\n const visit = async (directory: string): Promise<void> => {\n const directories: Promise<void>[] = [];\n for (const entry of await readdir(directory, { withFileTypes: true })) {\n const file = path.join(directory, entry.name);\n if (entry.isDirectory()) {\n if (!exclude(entry.name)) {\n directories.push(visit(file));\n }\n } else if (entry.name.endsWith('.brm')) {\n result.push(file.split(path.sep).join('/'));\n }\n }\n await Promise.all(directories);\n };\n await visit(root);\n return result.toSorted();\n}\n\n/**\n * Finds every file of server functions under a directory: a script whose\n * first statement is `'use server'`.\n */\nexport async function findServerFiles(\n root: string,\n exclude: (directory: string) => boolean,\n): Promise<string[]> {\n const result: string[] = [];\n const visit = async (directory: string): Promise<void> => {\n const pending: Promise<void>[] = [];\n for (const entry of await readdir(directory, { withFileTypes: true })) {\n const file = path.join(directory, entry.name);\n if (entry.isDirectory()) {\n if (!exclude(entry.name)) {\n pending.push(visit(file));\n }\n } else if (isScriptFile(entry.name)) {\n pending.push(\n readFile(file, 'utf8').then((source) => {\n if (hasUseServer(source)) {\n result.push(file.split(path.sep).join('/'));\n }\n }),\n );\n }\n }\n await Promise.all(pending);\n };\n await visit(root);\n return result.toSorted();\n}\n"],"mappings":";;;;;;AASA,MAAM,SAAS;;AAGf,SAAgB,aAAa,QAAyB;CACpD,OAAO,2DAA2D,KAAK,MAAM;AAC/E;;AAGA,SAAgB,aAAa,MAAuB;CAClD,OACE,kBAAkB,KAAK,IAAI,KAAK,CAAC,KAAK,SAAS,OAAO,KAAK,CAAC,qBAAqB,KAAK,IAAI;AAE9F;;AAGA,SAAS,WAAW,MAAoD;CACtE,OAAO,MAAM,SAAS,6BAA6B,MAAM,SAAS;AACpE;;;;;;AAOA,SAAgB,cAAc,QAAgB,UAA4B;CACxE,MAAM,EAAE,SAAS,WAAW,UAAU,UAAU,QAA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AAW;IACtC,IAAI,aAAa,MAAM,GACrB,OAAO,KAAK,KAAK,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,GAAG,CAAC;GAE9C,CAAC,CACH;EAEJ;EACA,MAAM,QAAQ,IAAI,OAAO;CAC3B;CACA,MAAM,MAAM,IAAI;CAChB,OAAO,OAAO,SAAS;AACzB"}
1
+ {"version":3,"file":"files-DdT84mPy.js","names":[],"sources":["../src/server-files.ts","../src/files.ts"],"sourcesContent":["// Files of server functions. A `.ts` or `.js` file whose first statement is\n// `'use server'` holds functions that only run on the server. Its exports are\n// server functions: the browser gets a stub for each one, which calls the\n// server, and the code of the file never ships.\n\nimport { parseSync } from 'oxc-parser';\nimport { functionId } from './plan.ts';\n\n/** The import of the stubs, which call server functions with `rpc` of the core. */\nconst CLIENT = 'brumate/client';\n\n/** True for a file whose first statement is `'use server'`, after comments. */\nexport function hasUseServer(source: string): boolean {\n return /^(?:\\s|\\/\\/[^\\n]*\\n|\\/\\*[\\s\\S]*?\\*\\/)*(['\"])use server\\1/.test(source);\n}\n\n/** True for a path that can be a file of server functions. */\nexport function isScriptFile(path: string): boolean {\n return (\n /\\.[cm]?[jt]sx?$/.test(path) && !path.endsWith('.d.ts') && !/\\.brm\\.[cm]?[jt]s$/.test(path)\n );\n}\n\n/** True for a function expression or an arrow. */\nfunction isFunction(node: { type: string } | null | undefined): boolean {\n return node?.type === 'ArrowFunctionExpression' || node?.type === 'FunctionExpression';\n}\n\n/**\n * The names of the functions that a file of server functions exports.\n * Throws for an export that is not a function, because the browser can only\n * call a server function through its stub.\n */\nexport function serverExports(source: string, filename: string): string[] {\n const { program, errors } = parseSync(filename, source, { lang: 'ts' });\n if (errors[0]) {\n throw new Error(`${errors[0].message} (${filename})`);\n }\n const functions = new Set<string>();\n const values = new Set<string>();\n const local = new Map<string, 'function' | 'value'>();\n for (const statement of program.body) {\n const declaration =\n statement.type === 'ExportNamedDeclaration' ? statement.declaration : statement;\n if (declaration?.type === 'FunctionDeclaration' && declaration.id) {\n local.set(declaration.id.name, 'function');\n } else if (declaration?.type === 'VariableDeclaration') {\n for (const declarator of declaration.declarations) {\n if (declarator.id.type === 'Identifier') {\n local.set(declarator.id.name, isFunction(declarator.init) ? 'function' : 'value');\n }\n }\n }\n }\n for (const statement of program.body) {\n if (statement.type === 'ExportDefaultDeclaration') {\n const value = statement.declaration;\n if (value.type === 'FunctionDeclaration' || isFunction(value)) {\n functions.add('default');\n } else {\n values.add('default');\n }\n } else if (statement.type === 'ExportNamedDeclaration') {\n if (statement.exportKind === 'type') {\n continue;\n }\n const declaration = statement.declaration;\n if (declaration?.type === 'FunctionDeclaration' && declaration.id) {\n functions.add(declaration.id.name);\n } else if (declaration?.type === 'VariableDeclaration') {\n for (const declarator of declaration.declarations) {\n if (declarator.id.type === 'Identifier') {\n (isFunction(declarator.init) ? functions : values).add(declarator.id.name);\n }\n }\n } else if (declaration && !declaration.type.startsWith('TS')) {\n values.add('a class');\n }\n for (const specifier of statement.specifiers) {\n if (specifier.exportKind === 'type') {\n continue;\n }\n const name =\n specifier.exported.type === 'Identifier'\n ? specifier.exported.name\n : specifier.exported.value;\n const from = specifier.local.type === 'Identifier' ? specifier.local.name : '';\n (local.get(from) === 'function' && !statement.source ? functions : values).add(name);\n }\n } else if (statement.type === 'ExportAllDeclaration') {\n values.add('*');\n }\n }\n if (values.size > 0) {\n throw new Error(\n `A 'use server' file exports only functions, because the browser calls them on the server. ${[...values].join(', ')} of ${filename} is not one`,\n );\n }\n return [...functions];\n}\n\n/** The module that the browser gets in place of a file of server functions. */\nexport function serverStubs(\n source: string,\n filename: string,\n id: string,\n hideNames = false,\n): string {\n const lines = [`import { rpc } from ${JSON.stringify(CLIENT)};`];\n for (const name of serverExports(source, filename)) {\n const call = `(...args) => rpc(${JSON.stringify(functionId(id, name, hideNames))}, args)`;\n lines.push(name === 'default' ? `export default ${call};` : `export const ${name} = ${call};`);\n }\n return `${lines.join('\\n')}\\n`;\n}\n\n/**\n * The module that the server runs for a file of server functions: the file,\n * with each exported function wrapped, so its calls while a page renders\n * share a result when their arguments are the same. Offsets stay the same.\n */\nexport function serverModule(source: string, filename: string, id: string): string {\n const { program } = parseSync(filename, source, { lang: 'ts' });\n // Local names of exported functions, with the name that each is exported as.\n const wrapped = new Map<string, string>();\n const declarations = new Map<string, 'function' | 'const'>();\n let code = source;\n for (const statement of program.body) {\n const declaration =\n statement.type === 'ExportNamedDeclaration' ? statement.declaration : statement;\n if (declaration?.type === 'FunctionDeclaration' && declaration.id) {\n declarations.set(declaration.id.name, 'function');\n } else if (declaration?.type === 'VariableDeclaration') {\n for (const declarator of declaration.declarations) {\n if (declarator.id.type === 'Identifier' && isFunction(declarator.init)) {\n declarations.set(declarator.id.name, 'const');\n }\n }\n }\n }\n const letOf = (declaration: { start: number; kind: string }): void => {\n // `const` becomes `let `, so the function can be wrapped and offsets stay the same.\n if (declaration.kind === 'const') {\n code = `${code.slice(0, declaration.start)}let ${code.slice(declaration.start + 5)}`;\n }\n };\n for (const statement of program.body) {\n if (\n statement.type !== 'ExportNamedDeclaration' ||\n statement.source ||\n statement.exportKind === 'type'\n ) {\n continue;\n }\n const declaration = statement.declaration;\n if (declaration?.type === 'FunctionDeclaration' && declaration.id) {\n wrapped.set(declaration.id.name, declaration.id.name);\n } else if (declaration?.type === 'VariableDeclaration') {\n for (const declarator of declaration.declarations) {\n if (declarator.id.type === 'Identifier' && isFunction(declarator.init)) {\n wrapped.set(declarator.id.name, declarator.id.name);\n letOf(declaration);\n }\n }\n }\n for (const specifier of statement.specifiers) {\n const local = specifier.local.type === 'Identifier' ? specifier.local.name : '';\n const exported =\n specifier.exported.type === 'Identifier'\n ? specifier.exported.name\n : specifier.exported.value;\n if (declarations.has(local)) {\n wrapped.set(local, exported);\n }\n }\n }\n // A `const` arrow that `export { name }` exports is declared with `let` too.\n for (const statement of program.body) {\n if (statement.type === 'VariableDeclaration') {\n for (const declarator of statement.declarations) {\n if (declarator.id.type === 'Identifier' && wrapped.has(declarator.id.name)) {\n letOf(statement);\n }\n }\n }\n }\n if (wrapped.size === 0) {\n return source;\n }\n const lines = [\"import { dedupe as __brumateDedupe } from 'brumate/server';\"];\n for (const [local, exported] of wrapped) {\n lines.push(`${local} = __brumateDedupe(${local}, ${JSON.stringify(`${id}#${exported}`)});`);\n }\n return `${code}\\n${lines.join('\\n')}\\n`;\n}\n","import { readFile, readdir } from 'node:fs/promises';\nimport path from 'node:path';\nimport { hasUseServer, isScriptFile } from './server-files.ts';\n\n/** Skips `node_modules`, `dist` and hidden directories when looking for `.brm` files. */\nexport function defaultExclude(directory: string): boolean {\n return directory === 'node_modules' || directory === 'dist' || directory.startsWith('.');\n}\n\n/** Finds every `.brm` file under a directory, as absolute paths with forward slashes. */\nexport async function findFiles(\n root: string,\n exclude: (directory: string) => boolean,\n): Promise<string[]> {\n const result: string[] = [];\n const visit = async (directory: string): Promise<void> => {\n const directories: Promise<void>[] = [];\n for (const entry of await readdir(directory, { withFileTypes: true })) {\n const file = path.join(directory, entry.name);\n if (entry.isDirectory()) {\n if (!exclude(entry.name)) {\n directories.push(visit(file));\n }\n } else if (entry.name.endsWith('.brm')) {\n result.push(file.split(path.sep).join('/'));\n }\n }\n await Promise.all(directories);\n };\n await visit(root);\n return result.toSorted();\n}\n\n/**\n * Finds every file of server functions under a directory: a script whose\n * first statement is `'use server'`.\n */\nexport async function findServerFiles(\n root: string,\n exclude: (directory: string) => boolean,\n): Promise<string[]> {\n const result: string[] = [];\n const visit = async (directory: string): Promise<void> => {\n const pending: Promise<void>[] = [];\n for (const entry of await readdir(directory, { withFileTypes: true })) {\n const file = path.join(directory, entry.name);\n if (entry.isDirectory()) {\n if (!exclude(entry.name)) {\n pending.push(visit(file));\n }\n } else if (isScriptFile(entry.name)) {\n pending.push(\n readFile(file, 'utf8').then((source) => {\n if (hasUseServer(source)) {\n result.push(file.split(path.sep).join('/'));\n }\n }),\n );\n }\n }\n await Promise.all(pending);\n };\n await visit(root);\n return result.toSorted();\n}\n\n/**\n * Finds every script under a directory, such as `.ts` and `.brm.ts` files, as\n * absolute paths with forward slashes, without reading them.\n */\nexport async function findScripts(\n root: string,\n exclude: (directory: string) => boolean,\n): Promise<string[]> {\n const result: string[] = [];\n const visit = async (directory: string): Promise<void> => {\n const directories: Promise<void>[] = [];\n for (const entry of await readdir(directory, { withFileTypes: true })) {\n const file = path.join(directory, entry.name);\n if (entry.isDirectory()) {\n if (!exclude(entry.name)) {\n directories.push(visit(file));\n }\n } else if (/\\.[cm]?[jt]sx?$/.test(entry.name) && !entry.name.endsWith('.d.ts')) {\n result.push(file.split(path.sep).join('/'));\n }\n }\n await Promise.all(directories);\n };\n await visit(root);\n return result.toSorted();\n}\n"],"mappings":";;;;;;AASA,MAAM,SAAS;;AAGf,SAAgB,aAAa,QAAyB;CACpD,OAAO,2DAA2D,KAAK,MAAM;AAC/E;;AAGA,SAAgB,aAAa,MAAuB;CAClD,OACE,kBAAkB,KAAK,IAAI,KAAK,CAAC,KAAK,SAAS,OAAO,KAAK,CAAC,qBAAqB,KAAK,IAAI;AAE9F;;AAGA,SAAS,WAAW,MAAoD;CACtE,OAAO,MAAM,SAAS,6BAA6B,MAAM,SAAS;AACpE;;;;;;AAOA,SAAgB,cAAc,QAAgB,UAA4B;CACxE,MAAM,EAAE,SAAS,WAAW,UAAU,UAAU,QAAQ,EAAE,MAAM,KAAK,CAAC;CACtE,IAAI,OAAO,IACT,MAAM,IAAI,MAAM,GAAG,OAAO,EAAE,CAAC,QAAQ,IAAI,SAAS,EAAE;CAEtD,MAAM,4BAAY,IAAI,IAAY;CAClC,MAAM,yBAAS,IAAI,IAAY;CAC/B,MAAM,wBAAQ,IAAI,IAAkC;CACpD,KAAK,MAAM,aAAa,QAAQ,MAAM;EACpC,MAAM,cACJ,UAAU,SAAS,2BAA2B,UAAU,cAAc;EACxE,IAAI,aAAa,SAAS,yBAAyB,YAAY,IAC7D,MAAM,IAAI,YAAY,GAAG,MAAM,UAAU;OACpC,IAAI,aAAa,SAAS,uBAC1B;Q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,OAAO,KAAK,KAAK,WAAW,MAAM,IAAI;GAC5C,IAAI,MAAM,YAAY,GAChB;QAAA,CAAC,QAAQ,MAAM,IAAI,GACrB,YAAY,KAAK,MAAM,IAAI,CAAC;GAAA,OAEzB,IAAI,kBAAkB,KAAK,MAAM,IAAI,KAAK,CAAC,MAAM,KAAK,SAAS,OAAO,GAC3E,OAAO,KAAK,KAAK,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,GAAG,CAAC;EAE9C;EACA,MAAM,QAAQ,IAAI,WAAW;CAC/B;CACA,MAAM,MAAM,IAAI;CAChB,OAAO,OAAO,SAAS;AACzB"}
@@ -1,7 +1,13 @@
1
1
  //#region src/runtime/html.ts
2
2
  const RAW = Symbol.for("brumate.raw");
3
+ var RawHTML = class {
4
+ [RAW];
5
+ constructor(html) {
6
+ this[RAW] = html;
7
+ }
8
+ };
3
9
  function raw(html) {
4
- return { [RAW]: html };
10
+ return new RawHTML(html);
5
11
  }
6
12
  function isRaw(value) {
7
13
  return typeof value === "object" && value !== null && RAW in value;
@@ -15,11 +21,12 @@ const ESCAPES = {
15
21
  ">": "&gt;",
16
22
  "\"": "&quot;"
17
23
  };
24
+ const toEscape = (char) => ESCAPES[char];
18
25
  function escape(value) {
19
- return value.replace(/[&<>]/g, (char) => ESCAPES[char]);
26
+ return /[&<>]/.test(value) ? value.replace(/[&<>]/g, toEscape) : value;
20
27
  }
21
28
  function escapeAttribute(value) {
22
- return value.replace(/[&<"]/g, (char) => ESCAPES[char]);
29
+ return /[&<"]/.test(value) ? value.replace(/[&<"]/g, toEscape) : value;
23
30
  }
24
31
  /** Renders a value inserted in markup. Promises are not awaited. */
25
32
  function insertValue(value) {
@@ -28,13 +35,43 @@ function insertValue(value) {
28
35
  if (Array.isArray(value)) return value.map(insertValue).join("");
29
36
  return escape(String(value));
30
37
  }
38
+ /**
39
+ * Renders a value as the text of an element whose content is text, such as
40
+ * a `<textarea>`, as `insertValue` does but without escaping.
41
+ */
42
+ function textValue(value) {
43
+ if (isRaw(value)) return value[RAW];
44
+ if (value === null || value === void 0 || typeof value === "boolean") return "";
45
+ if (Array.isArray(value)) return value.map(textValue).join("");
46
+ return String(value);
47
+ }
31
48
  function toKebabCase(name) {
32
49
  return name.startsWith("--") ? name : name.replace(/[A-Z]/g, (char) => `-${char.toLowerCase()}`);
33
50
  }
34
51
  function classValue(value) {
35
- if (Array.isArray(value)) return value.map(classValue).filter(Boolean).join(" ");
36
- if (typeof value === "object" && value !== null) return Object.entries(value).filter(([, enabled]) => enabled).map(([name]) => name).join(" ");
37
- return value ? String(value) : "";
52
+ if (typeof value !== "object" || value === null) return value ? String(value) : "";
53
+ let text = "";
54
+ if (Array.isArray(value)) {
55
+ for (const item of value) {
56
+ const part = classValue(item);
57
+ if (part !== "") text = text === "" ? part : `${text} ${part}`;
58
+ }
59
+ return text;
60
+ }
61
+ let first = true;
62
+ for (const name in value) if (Object.hasOwn(value, name) && value[name]) {
63
+ text = first ? name : `${text} ${name}`;
64
+ first = false;
65
+ }
66
+ return text;
67
+ }
68
+ /**
69
+ * Renders a `class` attribute from classes that each have a space before
70
+ * them, which the compiler builds from a literal class value. The classes
71
+ * are escaped already. No class renders nothing.
72
+ */
73
+ function classAttribute(classes) {
74
+ return classes === "" ? "" : ` class="${classes.slice(1)}"`;
38
75
  }
39
76
  function styleValue(value) {
40
77
  if (typeof value === "object" && value !== null) return Object.entries(value).filter(([, item]) => item !== null && item !== void 0 && item !== false).map(([name, item]) => `${toKebabCase(name)}:${String(item)}`).join(";");
@@ -76,7 +113,7 @@ function vars(variables, own) {
76
113
  }
77
114
  /** Returns a `<style>` element for a component's stylesheet. */
78
115
  function styleElement(id, css) {
79
- return `<style data-brm="${escapeAttribute(id)}">${css.replace(/<\/style/gi, "<\\/style")}</style>`;
116
+ return `<style b-style="${escapeAttribute(id)}">${css.replace(/<\/style/gi, "<\\/style")}</style>`;
80
117
  }
81
118
  /** Renders an object of attributes. */
82
119
  function spread(attributes) {
@@ -106,10 +143,10 @@ const VOID_ELEMENTS = /* @__PURE__ */ new Set([
106
143
  */
107
144
  function actionAttributes(prefix, name, id, method, result) {
108
145
  const methodText = method ? ` ${method}="post"` : "";
109
- if (result !== void 0) return ` ${name}="?__action=${encodeURIComponent(id)}"${methodText} data-action="${escapeAttribute(id)}" data-result="${escapeAttribute(result)}"`;
146
+ if (result !== void 0) return ` ${name}="?__action=${encodeURIComponent(id)}"${methodText} b-action="${escapeAttribute(id)}" b-result="${escapeAttribute(result)}"`;
110
147
  return ` ${name}="${escapeAttribute(`${prefix}/${encodeURIComponent(id)}`)}"${methodText}`;
111
148
  }
112
149
  //#endregion
113
- export { attributeText as a, insertValue as c, rawHTML as d, spread as f, attribute as i, isRaw as l, vars as m, actionAttributes as n, escape as o, styleElement as p, affix as r, escapeAttribute as s, VOID_ELEMENTS as t, raw as u };
150
+ export { vars as _, attributeText as a, escape as c, isRaw as d, raw as f, textValue as g, styleElement as h, attribute as i, escapeAttribute as l, spread as m, actionAttributes as n, classAttribute as o, rawHTML as p, affix as r, classValue as s, VOID_ELEMENTS as t, insertValue as u };
114
151
 
115
- //# sourceMappingURL=html-CxWpXngy.js.map
152
+ //# sourceMappingURL=html-DEeoepg3.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"html-DEeoepg3.js","names":[],"sources":["../src/runtime/html.ts"],"sourcesContent":["// HTML string helpers that the server and the client both use.\n\nconst RAW: unique symbol = Symbol.for('brumate.raw');\n\n/** HTML that is inserted as it is, such as the output of a template. */\nexport interface Raw {\n [RAW]: string;\n}\n\n// A class, not an object literal, so serializers can skip their test for raw HTML on plain objects.\nclass RawHTML implements Raw {\n readonly [RAW]: string;\n\n constructor(html: string) {\n this[RAW] = html;\n }\n}\n\nexport function raw(html: string): Raw {\n return new RawHTML(html);\n}\n\nexport function isRaw(value: unknown): value is Raw {\n return typeof value === 'object' && value !== null && RAW in value;\n}\n\nexport function rawHTML(value: Raw): string {\n return value[RAW];\n}\n\nconst ESCAPES: Record<string, string> = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;' };\n\nconst toEscape = (char: string): string => ESCAPES[char]!;\n\n// Most text has nothing to escape, so a test without the global flag skips the replace.\nexport function escape(value: string): string {\n return /[&<>]/.test(value) ? value.replace(/[&<>]/g, toEscape) : value;\n}\n\nexport function escapeAttribute(value: string): string {\n return /[&<\"]/.test(value) ? value.replace(/[&<\"]/g, toEscape) : value;\n}\n\n/** Renders a value inserted in markup. Promises are not awaited. */\nexport function insertValue(value: unknown): string {\n if (isRaw(value)) {\n return value[RAW];\n }\n if (value === null || value === undefined || typeof value === 'boolean') {\n return '';\n }\n if (Array.isArray(value)) {\n return value.map(insertValue).join('');\n }\n return escape(String(value));\n}\n\n/**\n * Renders a value as the text of an element whose content is text, such as\n * a `<textarea>`, as `insertValue` does but without escaping.\n */\nexport function textValue(value: unknown): string {\n if (isRaw(value)) {\n return value[RAW];\n }\n if (value === null || value === undefined || typeof value === 'boolean') {\n return '';\n }\n if (Array.isArray(value)) {\n return value.map(textValue).join('');\n }\n return String(value);\n}\n\nfunction toKebabCase(name: string): string {\n return name.startsWith('--') ? name : name.replace(/[A-Z]/g, (char) => `-${char.toLowerCase()}`);\n}\n\nexport function classValue(value: unknown): string {\n if (typeof value !== 'object' || value === null) {\n return value ? String(value) : '';\n }\n let text = '';\n if (Array.isArray(value)) {\n for (const item of value) {\n const part = classValue(item);\n if (part !== '') {\n text = text === '' ? part : `${text} ${part}`;\n }\n }\n return text;\n }\n // An empty name still adds a space between its neighbours, as in a join.\n let first = true;\n for (const name in value) {\n if (Object.hasOwn(value, name) && (value as Record<string, unknown>)[name]) {\n text = first ? name : `${text} ${name}`;\n first = false;\n }\n }\n return text;\n}\n\n/**\n * Renders a `class` attribute from classes that each have a space before\n * them, which the compiler builds from a literal class value. The classes\n * are escaped already. No class renders nothing.\n */\nexport function classAttribute(classes: string): string {\n return classes === '' ? '' : ` class=\"${classes.slice(1)}\"`;\n}\n\nfunction styleValue(value: unknown): string {\n if (typeof value === 'object' && value !== null) {\n return Object.entries(value)\n .filter(([, item]) => item !== null && item !== undefined && item !== false)\n .map(([name, item]) => `${toKebabCase(name)}:${String(item)}`)\n .join(';');\n }\n return String(value);\n}\n\n/**\n * Returns the text of an attribute, or undefined if the attribute is not\n * rendered. `true` renders as an empty value.\n */\nexport function attributeText(name: string, value: unknown): string | undefined {\n if (value === null || value === undefined || value === false || typeof value === 'function') {\n return undefined;\n }\n if (value === true) {\n return '';\n }\n if (name === 'class') {\n const text = classValue(value);\n return text === '' ? undefined : text;\n }\n return name === 'style' ? styleValue(value) : String(value);\n}\n\n/** Renders one attribute, with a leading space. */\nexport function attribute(name: string, value: unknown): string {\n const text = attributeText(name, value);\n if (text === undefined) {\n return '';\n }\n return value === true ? ` ${name}` : ` ${name}=\"${escapeAttribute(text)}\"`;\n}\n\n/**\n * Returns the value of a style variable with text around it, such as `12px`\n * for `${size}px`. A value that sets no variable stays as it is.\n */\nexport function affix(prefix: string, value: unknown, suffix: string): unknown {\n return value === null || value === undefined || value === false\n ? value\n : `${prefix}${String(value)}${suffix}`;\n}\n\n/** Returns a style with custom properties before an element's own style. */\nexport function vars(variables: Record<string, unknown>, own: unknown): string {\n const parts: string[] = [];\n for (const [name, value] of Object.entries(variables)) {\n if (value !== null && value !== undefined && value !== false) {\n parts.push(`${name}:${String(value)}`);\n }\n }\n const rest = own === null || own === undefined || own === false ? '' : styleValue(own);\n if (rest) {\n parts.push(rest);\n }\n return parts.join(';');\n}\n\n/** Returns a `<style>` element for a component's stylesheet. */\nexport function styleElement(id: string, css: string): string {\n return `<style b-style=\"${escapeAttribute(id)}\">${css.replace(/<\\/style/gi, '<\\\\/style')}</style>`;\n}\n\n/** Renders an object of attributes. */\nexport function spread(attributes: Record<string, unknown>): string {\n let result = '';\n for (const [name, value] of Object.entries(attributes)) {\n if (name !== 'children' && !/^on[A-Z]/.test(name)) {\n result += attribute(name, value);\n }\n }\n return result;\n}\n\nexport const VOID_ELEMENTS: Set<string> = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'source',\n 'track',\n 'wbr',\n]);\n\n/**\n * Renders the attributes of a form that posts to a server function, such as\n * ` action=\"/_brumate/App_1abc%23save\" method=\"post\"`. `method` is the name of\n * the method attribute to add, if the element has none.\n */\nexport function actionAttributes(\n prefix: string,\n name: string,\n id: string,\n method?: string,\n result?: string,\n): string {\n const methodText = method ? ` ${method}=\"post\"` : '';\n if (result !== undefined) {\n // The form posts to its page, which renders with the result. With the\n // loader, the result is written into the `$action` at `result` instead.\n return ` ${name}=\"?__action=${encodeURIComponent(id)}\"${methodText} b-action=\"${escapeAttribute(id)}\" b-result=\"${escapeAttribute(result)}\"`;\n }\n const url = `${prefix}/${encodeURIComponent(id)}`;\n return ` ${name}=\"${escapeAttribute(url)}\"${methodText}`;\n}\n"],"mappings":";AAEA,MAAM,MAAqB,OAAO,IAAI,aAAa;AAQnD,IAAM,UAAN,MAA6B;CAC3B,CAAU;CAEV,YAAY,MAAc;EACxB,KAAK,OAAO;CACd;AACF;AAEA,SAAgB,IAAI,MAAmB;CACrC,OAAO,IAAI,QAAQ,IAAI;AACzB;AAEA,SAAgB,MAAM,OAA8B;CAClD,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,OAAO;AAC/D;AAEA,SAAgB,QAAQ,OAAoB;CAC1C,OAAO,MAAM;AACf;AAEA,MAAM,UAAkC;CAAE,KAAK;CAAS,KAAK;CAAQ,KAAK;CAAQ,MAAK;AAAS;AAEhG,MAAM,YAAY,SAAyB,QAAQ;AAGnD,SAAgB,OAAO,OAAuB;CAC5C,OAAO,QAAQ,KAAK,KAAK,IAAI,MAAM,QAAQ,UAAU,QAAQ,IAAI;AACnE;AAEA,SAAgB,gBAAgB,OAAuB;CACrD,OAAO,QAAQ,KAAK,KAAK,IAAI,MAAM,QAAQ,UAAU,QAAQ,IAAI;AACnE;;AAGA,SAAgB,YAAY,OAAwB;CAClD,IAA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,IAAI;CAEjB,OAAO,MAAM,KAAK,GAAG;AACvB;;AAGA,SAAgB,aAAa,IAAY,KAAqB;CAC5D,OAAO,mBAAmB,gBAAgB,EAAE,EAAE,IAAI,IAAI,QAAQ,cAAc,WAAW,EAAE;AAC3F;;AAGA,SAAgB,OAAO,YAA6C;CAClE,IAAI,SAAS;CACb,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,UAAU,GACnD,IAAI,SAAS,cAAc,CAAC,WAAW,KAAK,IAAI,GAC9C,UAAU,UAAU,MAAM,KAAK;CAGnC,OAAO;AACT;AAEA,MAAa,gCAA6B,IAAI,IAAI;CAChD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;AAOD,SAAgB,iBACd,QACA,MACA,IACA,QACA,QACQ;CACR,MAAM,aAAa,SAAS,IAAI,OAAO,WAAW;CAClD,IAAI,WAAW,KAAA,GAGb,OAAO,IAAI,KAAK,cAAc,mBAAmB,EAAE,EAAE,GAAG,WAAW,aAAa,gBAAgB,EAAE,EAAE,cAAc,gBAAgB,MAAM,EAAE;CAG5I,OAAO,IAAI,KAAK,IAAI,gBAAgB,GADrB,OAAO,GAAG,mBAAmB,EAAE,GACP,EAAE,GAAG;AAC9C"}
@@ -11,6 +11,18 @@ declare function escape(value: string): string;
11
11
  declare function escapeAttribute(value: string): string;
12
12
  /** Renders a value inserted in markup. Promises are not awaited. */
13
13
  declare function insertValue(value: unknown): string;
14
+ /**
15
+ * Renders a value as the text of an element whose content is text, such as
16
+ * a `<textarea>`, as `insertValue` does but without escaping.
17
+ */
18
+ declare function textValue(value: unknown): string;
19
+ declare function classValue(value: unknown): string;
20
+ /**
21
+ * Renders a `class` attribute from classes that each have a space before
22
+ * them, which the compiler builds from a literal class value. The classes
23
+ * are escaped already. No class renders nothing.
24
+ */
25
+ declare function classAttribute(classes: string): string;
14
26
  /**
15
27
  * Returns the text of an attribute, or undefined if the attribute is not
16
28
  * rendered. `true` renders as an empty value.
@@ -37,5 +49,5 @@ declare const VOID_ELEMENTS: Set<string>;
37
49
  */
38
50
  declare function actionAttributes(prefix: string, name: string, id: string, method?: string, result?: string): string;
39
51
  //#endregion
40
- export { attribute as a, escapeAttribute as c, raw as d, rawHTML as f, vars as h, affix as i, insertValue as l, styleElement as m, VOID_ELEMENTS as n, attributeText as o, spread as p, actionAttributes as r, escape as s, Raw as t, isRaw as u };
41
- //# sourceMappingURL=html-DV-Tezgq.d.ts.map
52
+ export { textValue as _, attribute as a, classValue as c, insertValue as d, isRaw as f, styleElement as g, spread as h, affix as i, escape as l, rawHTML as m, VOID_ELEMENTS as n, attributeText as o, raw as p, actionAttributes as r, classAttribute as s, Raw as t, escapeAttribute as u, vars as v };
53
+ //# sourceMappingURL=html-Du8jY2Cc.d.ts.map