foldkit-plus 0.19.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -198,11 +198,13 @@ const readings = await Cpu.budget(stack.cpu, {
198
198
  ```
199
199
 
200
200
  Each route is asked once, then `runs` (5) times more, one request at a time,
201
- each response read in full. Over budget, it throws with every route's
202
- reading; a 5xx throws too, since a failure costs nothing. `cold` is the
203
- route's first request in the call, so in a fresh stack it is a cold
204
- isolate's: code not yet optimized, and work kept per isolate (a compiled
205
- query, Auth) done for the first time.
201
+ each response read in full. Every warm request is checked, since a deployed
202
+ limit applies to each rather than to their mean: `warm` in a reading is the
203
+ most one spent. Over budget, it throws with every route's reading; a 5xx
204
+ throws too, since a failure costs nothing. `cold` is the route's first
205
+ request in the call, so in a fresh stack it is a cold isolate's: code not yet
206
+ optimized, and work kept per isolate (a compiled query, Auth) done for the
207
+ first time.
206
208
 
207
209
  There are two meters:
208
210
 
@@ -0,0 +1 @@
1
+ export * from "foldkit-mixins/vite";
@@ -0,0 +1,2 @@
1
+ export * from "foldkit-mixins/vite";
2
+ export {};
@@ -1 +1 @@
1
- {"version":3,"file":"playwright.d.mts","names":[],"sources":["../../src/testing/playwright.ts"],"mappings":";;;;;;;;iBA6EiB;WACN,gBAAgB;;iBAGV;;WAEN,WAAW;;WAEX,OAAO;;;;;;;;WAQP,0BAA0B;;WAE1B,kBAAkB;;;;;;WAMlB,OAAO,SAAS;;WAEhB,SAAS,SAAS;;;;;;;;;;;;;;;;;;;;;cAwIvB,aAAU,MAAgB,MAAI,SAAW,sBAAoB;iBAiIlD;;WAEN,eAAe;;;;;;WAMf,cAAc;;;;;;;cA2CnB,aAAU,MAAgB,MAAI,SAAW,sBAAoB;;;;;cA6B7D,gBAAa,MAAU,gBAAc;;qBAU9B"}
1
+ {"version":3,"file":"playwright.d.mts","names":[],"sources":["../../src/testing/playwright.ts"],"mappings":";;;;;;;;iBA6EiB;WACN,gBAAgB;;iBAGV;;WAEN,WAAW;;WAEX,OAAO;;;;;;;;WAQP,0BAA0B;;WAE1B,kBAAkB;;;;;;WAMlB,OAAO,SAAS;;WAEhB,SAAS,SAAS;;;;;;;;;;;;;;;;;;;;;cAwIvB,aAAU,MAAgB,MAAI,SAAW,sBAAoB;iBAoIlD;;WAEN,eAAe;;;;;;WAMf,cAAc;;;;;;;cA2CnB,aAAU,MAAgB,MAAI,SAAW,sBAAoB;;;;;cA6B7D,gBAAa,MAAU,gBAAc;;qBAU9B"}
@@ -215,7 +215,7 @@ const optimistic = async (page, options) => {
215
215
  }) : new Promise(() => {});
216
216
  if (!await Promise.race([acted.then(() => true), deadline])) {
217
217
  release();
218
- await acted;
218
+ acted.catch(() => {});
219
219
  throw new Error(`optimistic: the action did not end within ${Math.max(hold, ACT_LIMIT)} ms, and every write is held until it does: does it wait for its own write's answer?`);
220
220
  }
221
221
  const missed = await shown;
@@ -1 +1 @@
1
- {"version":3,"file":"playwright.mjs","names":[],"sources":["../../src/testing/playwright.ts"],"sourcesContent":["/**\n * `foldkit-plus/testing/playwright`: what a user sees, asserted on a running\n * page. A write shows before the server answers, holds still until it is\n * answered, and stays after; a step never shows a given text, at any moment;\n * the page logs no error.\n *\n * Each checks the page as drawn, over the real network: it proves that the\n * whole application (server, hydration, persistence, the Worker) delivers a\n * property. Which Message breaks a read's property is\n * `foldkit-plus/remote/testing`'s `Trace`, which records every Model without\n * a browser; reach for it once one of these fails.\n *\n * Playwright is an optional peer of `foldkit-plus`, needed only for its types:\n * this module calls nothing but the `Page` it is given.\n */\nimport { Duration, Option, Schema } from 'effect'\nimport { RemoteJsonRequest } from 'foldkit-remote'\nimport type { ConsoleMessage, Locator, Page, Request, Route } from 'playwright'\n\nconst decodeRequest = Schema.decodeUnknownOption(Schema.fromJsonString(RemoteJsonRequest))\n\n/** The operation of a Remote request over HTTP, by the JSON request `Remote.http` sends. */\nconst remoteOperation = (request: Request): Option.Option<RemoteJsonRequest['operation']> => {\n const body = request.method() === 'POST' ? request.postData() : null\n return body === null ? Option.none() : Option.map(decodeRequest(body), sent => sent.operation)\n}\n\nconst isRemoteMutation = (request: Request): boolean =>\n Option.contains(remoteOperation(request), 'mutate')\n\nconst millis = (input: Duration.Input) => Duration.toMillis(Duration.fromInputUnsafe(input))\n\n/**\n * How long `act` may take at least before it is taken to wait for its own\n * write's answer. Only that case needs a limit, so it is far longer than a\n * click takes on a loaded runner, whatever `hold` is.\n */\nconst ACT_LIMIT = 10_000\n\n/**\n * Resolves once three frames in a row pass with no change to the document,\n * or after two seconds of changes: a Message an answer caused has been drawn.\n */\nconst quiet = (page: Page): Promise<void> =>\n page.evaluate(\n () =>\n new Promise<void>(resolve => {\n let calm = 0\n const observer = new MutationObserver(() => {\n calm = 0\n })\n const done = () => {\n observer.disconnect()\n resolve()\n }\n observer.observe(document, {\n childList: true,\n subtree: true,\n characterData: true,\n attributes: true,\n })\n setTimeout(done, 2000)\n const frame = () => {\n calm += 1\n if (calm >= 3) done()\n else requestAnimationFrame(frame)\n }\n requestAnimationFrame(frame)\n }),\n )\n\n/**\n * Writes that reach the server some way other than `Remote.http` (a port to a\n * SharedWorker, a sandbox in the page). The page holds its own answers (the\n * test opened it so), and `answered` resolves on the page's own evidence that\n * nothing it wrote is pending: an outbox emptied, a status gone.\n */\nexport interface PageWrites {\n readonly answered: () => Promise<unknown>\n}\n\nexport interface OptimisticOptions {\n /** The user's action that writes: a click, a key. */\n readonly act: () => Promise<unknown>\n /** What the page shows once the write is made. */\n readonly shows: Locator\n /**\n * What must hold still from the moment `shows` shows until the write is\n * answered and drawn: `'put'` (the default), each element `shows` resolves\n * to; a `Locator`, what it resolves to instead (the list around a row its\n * answer deliberately draws again); `'shown'`, nothing, so only that\n * `shows` shows again after the answer.\n */\n readonly stays?: 'put' | 'shown' | Locator\n /** How the writes travel: `'http'` (the default), `Remote.http`'s requests, held at the network. */\n readonly writes?: 'http' | PageWrites\n /**\n * How long each Remote mutation is held at the network at least: it is held\n * on until `act` has ended and `shows` has been looked for. `'3 seconds'`\n * unless given.\n */\n readonly hold?: Duration.Input\n /** How soon after `act` begins `shows` must show, while every write is held. `'1 second'` unless given. */\n readonly within?: Duration.Input\n}\n\n/** What the page script needs to keep what it watches apart from another watch's. */\ninterface StillWatch {\n readonly key: string\n}\n\n// Runs in the page over the elements to keep still. A node removed and put\n// back in one batch reads as attached in the callback, so removals and\n// `hidden` are replayed from the records; layout and visibility are sampled\n// every frame, as a reader sees them. Each element reports each kind of fault once.\nconst watchStill = (elements: ReadonlyArray<Element>, { key }: StillWatch): number => {\n const started = performance.now()\n const where = (element: Element) => {\n const box = element.getBoundingClientRect()\n return { x: box.left + window.scrollX, y: box.top + window.scrollY }\n }\n const named = (element: Element) => {\n const html = element.outerHTML.replace(/\\s+/g, ' ')\n return html.length > 80 ? `${html.slice(0, 77)}...` : html\n }\n const watched = elements.map(element => {\n const lineage = new Set<Node>()\n for (let node: Node | null = element; node !== null; node = node.parentNode) lineage.add(node)\n return { element, lineage, first: where(element), faults: new Map<string, string>() }\n })\n const fault = (each: (typeof watched)[number], kind: string, words: string) => {\n if (!each.faults.has(kind))\n each.faults.set(\n kind,\n `${named(each.element)} ${words}, ${Math.round(performance.now() - started)} ms after it showed`,\n )\n }\n const observer = new MutationObserver(records => {\n for (const record of records)\n for (const each of watched) {\n if ([...record.removedNodes].some(node => each.lineage.has(node)))\n fault(each, 'removed', 'was taken out of the page')\n if (\n record.type === 'attributes' &&\n record.attributeName === 'hidden' &&\n record.oldValue === null &&\n each.lineage.has(record.target)\n )\n fault(each, 'hidden', 'was hidden')\n }\n for (const each of watched)\n if (each.faults.has('removed') && each.element.isConnected)\n fault(each, 'moved', 'was taken out and put back')\n })\n observer.observe(document, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: ['hidden'],\n attributeOldValue: true,\n })\n let frame = 0\n const sample = () => {\n for (const each of watched) {\n if (!each.element.isConnected) continue\n if (!each.element.checkVisibility({ visibilityProperty: true }))\n fault(each, 'hidden', 'was hidden')\n const now = where(each.element)\n const dx = now.x - each.first.x\n const dy = now.y - each.first.y\n const away = [\n ...(Math.abs(dx) > 1 ? [`${Math.round(Math.abs(dx))}px ${dx < 0 ? 'left' : 'right'}`] : []),\n ...(Math.abs(dy) > 1 ? [`${Math.round(Math.abs(dy))}px ${dy < 0 ? 'up' : 'down'}`] : []),\n ]\n if (away.length > 0) fault(each, 'shifted', `moved ${away.join(' and ')}`)\n }\n frame = requestAnimationFrame(sample)\n }\n sample()\n Reflect.set(window, key, () => {\n Reflect.deleteProperty(window, key)\n observer.disconnect()\n cancelAnimationFrame(frame)\n return watched.map(each => ({\n element: each.element,\n name: named(each.element),\n faults: each.faults,\n }))\n })\n return elements.length\n}\n\n/**\n * Stops the watch and lists what went wrong. `now` is what the locator\n * resolves to once settled: a watched element gone from the page while one\n * that was not watched stands there was replaced, not only removed.\n */\nconst stopStill = (now: ReadonlyArray<Element>, { key }: StillWatch): ReadonlyArray<string> => {\n const report: ReadonlyArray<{\n readonly element: Element\n readonly name: string\n readonly faults: ReadonlyMap<string, string>\n }> = Reflect.apply(Reflect.get(window, key), undefined, [])\n const newcomer = now.some(element => !report.some(each => each.element === element))\n return report.flatMap(each => {\n const replaced = newcomer && !each.element.isConnected\n return [\n ...[...each.faults].flatMap(([kind, words]) =>\n replaced && kind === 'removed' ? [] : [words],\n ),\n ...(replaced ? [`${each.name} was replaced by a new element`] : []),\n ]\n })\n}\n\nconst stopIfWatching = ({ key }: StillWatch) => {\n const stop: unknown = Reflect.get(window, key)\n if (typeof stop === 'function') stop()\n}\n\n/**\n * The write shows before the server answers, holds still until it has been\n * answered and drawn, and still shows after.\n *\n * Every Remote mutation the page sends is held at the network until `act`\n * has ended and `shows` has been looked for, and for `hold` at least, so\n * what shows was drawn before any answer however long `act` takes;\n * `shows` must be visible within `within` of `act` beginning. From\n * then until settled, what `stays` names must stay in the page as the same\n * nodes, in the same place in their parent, within 1px of where they were\n * drawn, and visible. Settled is evidence, not a wait: no Remote request of\n * the page in flight (an answer can lead to more, such as a placed list's\n * first page under `verifyPredictions`), or `writes.answered`, then the page\n * quiet for three frames. An error the page logs meanwhile fails it too: a\n * `PredictionMismatch` is logged as one. Throws otherwise, when `act` sent\n * no Remote mutation over HTTP, since nothing was then held, and when `act`\n * has not ended 10 seconds (or `hold`, if longer) after it began: one that\n * waits for its own write's answer would wait for good.\n */\nconst optimistic = async (page: Page, options: OptimisticOptions): Promise<void> => {\n const writes = options.writes ?? 'http'\n const hold = millis(options.hold ?? '3 seconds')\n const within = millis(options.within ?? '1 second')\n // Opened once `shows` has been looked for and is watched: no write is\n // answered before, so nothing shown by then is an answer.\n let release = () => {}\n const looked = new Promise<void>(resolve => {\n release = resolve\n })\n const held: Array<Promise<void>> = []\n // Every Remote request from `act` on that is not yet answered.\n const inFlight = new Set<Request>()\n const sent = (request: Request) => {\n if (Option.isSome(remoteOperation(request))) inFlight.add(request)\n }\n // How many have been answered: a quiet that began before the last answer\n // may have ended before the page drew it.\n let answers = 0\n const done = (request: Request) => {\n if (inFlight.delete(request)) answers += 1\n }\n const errors: Array<string> = []\n const logged = (message: ConsoleMessage) => {\n if (message.type() === 'error') errors.push(message.text())\n }\n const thrown = (error: Error) => errors.push(String(error))\n // Let through after `hold`, once looked. The answer is awaited apart from the\n // handler: Playwright passes a request on to the next handler only once this one returns.\n const letThrough = async (route: Route) => {\n await Promise.all([new Promise(resume => setTimeout(resume, hold)), looked])\n await route.fallback()\n }\n const answered = async (request: Request) => {\n const response = await request.response()\n if (response !== null) await response.finished()\n }\n const route = await page.route('**/*', (route, request) => {\n if (writes !== 'http' || !isRemoteMutation(request)) return route.fallback()\n held.push(answered(request))\n return letThrough(route)\n })\n page.on('request', sent)\n page.on('requestfinished', done)\n page.on('requestfailed', done)\n page.on('console', logged)\n page.on('pageerror', thrown)\n const shows = String(options.shows)\n const stays = options.stays ?? 'put'\n const watched =\n stays === 'shown'\n ? Option.none<Locator>()\n : Option.some(stays === 'put' ? options.shows : stays)\n const watch: StillWatch = { key: `__foldkitStill${crypto.randomUUID().replaceAll('-', '')}` }\n let overdue: ReturnType<typeof setTimeout> | undefined\n try {\n const shown = options.shows.waitFor({ state: 'visible', timeout: within }).then(\n () => Option.none<unknown>(),\n (error: unknown) => Option.some(error),\n )\n const acted = Promise.resolve().then(options.act)\n // An action waiting for its own write's answer would wait for good.\n const deadline =\n writes === 'http'\n ? new Promise<false>(resolve => {\n overdue = setTimeout(resolve, Math.max(hold, ACT_LIMIT), false)\n })\n : new Promise<never>(() => {})\n const ended = await Promise.race([acted.then(() => true), deadline])\n if (!ended) {\n release()\n await acted\n throw new Error(\n `optimistic: the action did not end within ${Math.max(hold, ACT_LIMIT)} ms, and every write is held until it does: does it wait for its own write's answer?`,\n )\n }\n const missed = await shown\n if (Option.isSome(missed))\n throw new Error(`optimistic: ${shows} did not show within ${within} ms of the action`, {\n cause: missed.value,\n })\n if (Option.isSome(watched) && (await watched.value.evaluateAll(watchStill, watch)) === 0)\n throw new Error(`optimistic: ${String(watched.value)}, what stays, matches nothing`)\n release()\n if (writes === 'http') {\n if (held.length === 0)\n throw new Error(`optimistic: ${shows} showed, but the action sent no Remote mutation`)\n } else {\n await writes.answered()\n }\n // Every held write is in flight until answered, and an answer drawn can ask\n // for more: settled once the page asks nothing and stays quiet from after\n // the last answer. The network finishes before the page reads the answer,\n // and an app draws it on a later frame.\n for (;;) {\n const before = answers\n await quiet(page)\n if (inFlight.size === 0 && answers === before) break\n }\n if (Option.isSome(watched)) {\n const faults = await watched.value.evaluateAll(stopStill, watch)\n if (faults.length > 0)\n throw new Error(\n `optimistic: ${String(watched.value)} did not hold still until the write settled:\\n ${faults.join('\\n ')}`,\n )\n }\n if (!(await options.shows.isVisible()))\n throw new Error(\n `optimistic: ${shows} showed while the write was held, but not after its answer`,\n )\n if (errors.length > 0)\n throw new Error(\n `optimistic: the page logged an error while the write settled:\\n ${errors.join('\\n ')}`,\n )\n } finally {\n clearTimeout(overdue)\n release()\n // A check that failed before reading the watch leaves it sampling every frame.\n if (!page.isClosed()) await page.evaluate(stopIfWatching, watch)\n page.off('request', sent)\n page.off('requestfinished', done)\n page.off('requestfailed', done)\n page.off('console', logged)\n page.off('pageerror', thrown)\n await route.dispose()\n await Promise.allSettled(held)\n }\n}\n\nexport interface NeverShowsOptions {\n /** What the page must not show at any moment of `during`. */\n readonly text: string | RegExp\n /**\n * The steps to watch: a reload, a navigation away and back. End it on what\n * the page waits for (an answer, a row), since watching stops once it ends\n * and the page is quiet.\n */\n readonly during: () => Promise<unknown>\n}\n\n/** What the page script needs: the binding to report through, and the text as a pattern. */\ninterface Watch {\n readonly key: string\n readonly source: string\n readonly flags: string\n}\n\n// Runs in the page, in the open document and in each one loaded after: after\n// every change to the document, the rendered text (`innerText` leaves hidden\n// text out) is searched, so a text shown for one frame is seen, not sampled.\nconst watchText = ({ key, source, flags }: Watch) => {\n if (window !== window.top) return\n const pattern = new RegExp(source, flags)\n let reported = false\n const check = () => {\n if (reported) return\n const line = (document.body?.innerText ?? '').split('\\n').find(each => pattern.test(each))\n if (line === undefined) return\n reported = true\n Reflect.apply(Reflect.get(window, key), undefined, [line])\n }\n const observer = new MutationObserver(check)\n observer.observe(document, {\n childList: true,\n subtree: true,\n characterData: true,\n attributes: true,\n })\n Reflect.set(window, `${key}Stop`, () => observer.disconnect())\n check()\n}\n\nconst stopWatching = (key: string) =>\n Reflect.apply(Reflect.get(window, `${key}Stop`), undefined, [])\n\n/**\n * The page never shows `text` while `during` runs, nor until the page is\n * quiet after it: a cached page revisited never reads \"Loading…\", even for\n * one frame. Throws with the line that showed.\n */\nconst neverShows = async (page: Page, options: NeverShowsOptions): Promise<void> => {\n const key = `__foldkitNeverShows${crypto.randomUUID().replaceAll('-', '')}`\n const { text } = options\n const watch: Watch =\n typeof text === 'string'\n ? { key, source: text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'), flags: '' }\n : { key, source: text.source, flags: text.flags }\n const shown: Array<string> = []\n const binding = await page.exposeBinding(key, (_, line: string) => {\n shown.push(line)\n })\n const script = await page.addInitScript(watchText, watch)\n try {\n await page.evaluate(watchText, watch)\n await options.during()\n await quiet(page)\n } finally {\n await script.dispose()\n if (!page.isClosed()) await page.evaluate(stopWatching, key)\n await binding.dispose()\n }\n if (shown.length > 0)\n throw new Error(`neverShows: the page showed ${String(text)}: \"${shown[0]}\"`)\n}\n\n/**\n * Collects every error the page logs (`console.error`) and every exception it\n * does not catch, from now until the page closes. Read the list at the end.\n */\nconst consoleErrors = (page: Page): (() => ReadonlyArray<string>) => {\n const errors: Array<string> = []\n page.on('console', message => {\n if (message.type() === 'error') errors.push(message.text())\n })\n page.on('pageerror', error => errors.push(String(error)))\n return () => [...errors]\n}\n\n/** Assertions on what a running page shows, for Playwright. */\nexport const Behaviors = { optimistic, neverShows, consoleErrors } as const\n"],"mappings":";;;;;;;;;;;;;;;;;;AAmBA,MAAM,gBAAgB,OAAO,oBAAoB,OAAO,eAAe,iBAAiB,CAAC;;AAGzF,MAAM,mBAAmB,YAAoE;CAC3F,MAAM,OAAO,QAAQ,OAAO,MAAM,SAAS,QAAQ,SAAS,IAAI;CAChE,OAAO,SAAS,OAAO,OAAO,KAAK,IAAI,OAAO,IAAI,cAAc,IAAI,IAAG,SAAQ,KAAK,SAAS;AAC/F;AAEA,MAAM,oBAAoB,YACxB,OAAO,SAAS,gBAAgB,OAAO,GAAG,QAAQ;AAEpD,MAAM,UAAU,UAA0B,SAAS,SAAS,SAAS,gBAAgB,KAAK,CAAC;;;;;;AAO3F,MAAM,YAAY;;;;;AAMlB,MAAM,SAAS,SACb,KAAK,eAED,IAAI,SAAc,YAAW;CAC3B,IAAI,OAAO;CACX,MAAM,WAAW,IAAI,uBAAuB;EAC1C,OAAO;CACT,CAAC;CACD,MAAM,aAAa;EACjB,SAAS,WAAW;EACpB,QAAQ;CACV;CACA,SAAS,QAAQ,UAAU;EACzB,WAAW;EACX,SAAS;EACT,eAAe;EACf,YAAY;CACd,CAAC;CACD,WAA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C,WAAW,KAAK,EAAE;CACxE,MAAM,EAAE,SAAS;CACjB,MAAM,QACJ,OAAO,SAAS,WACZ;EAAE;EAAK,QAAQ,KAAK,QAAQ,uBAAuB,MAAM;EAAG,OAAO;CAAG,IACtE;EAAE;EAAK,QAAQ,KAAK;EAAQ,OAAO,KAAK;CAAM;CACpD,MAAM,QAAuB,CAAC;CAC9B,MAAM,UAAU,MAAM,KAAK,cAAc,MAAM,GAAG,SAAiB;EACjE,MAAM,KAAK,IAAI;CACjB,CAAC;CACD,MAAM,SAAS,MAAM,KAAK,cAAc,WAAW,KAAK;CACxD,IAAI;EACF,MAAM,KAAK,SAAS,WAAW,KAAK;EACpC,MAAM,QAAQ,OAAO;EACrB,MAAM,MAAM,IAAI;CAClB,UAAU;EACR,MAAM,OAAO,QAAQ;EACrB,IAAI,CAAC,KAAK,SAAS,GAAG,MAAM,KAAK,SAAS,cAAc,GAAG;EAC3D,MAAM,QAAQ,QAAQ;CACxB;CACA,IAAI,MAAM,SAAS,GACjB,MAAM,IAAI,MAAM,+BAA+B,OAAO,IAAI,EAAE,KAAK,MAAM,GAAG,EAAE;AAChF;;;;;AAMA,MAAM,iBAAiB,SAA8C;CACnE,MAAM,SAAwB,CAAC;CAC/B,KAAK,GAAG,YAAW,YAAW;EAC5B,IAAI,QAAQ,KAAK,MAAM,SAAS,OAAO,KAAK,QAAQ,KAAK,CAAC;CAC5D,CAAC;CACD,KAAK,GAAG,cAAa,UAAS,OAAO,KAAK,OAAO,KAAK,CAAC,CAAC;CACxD,aAAa,CAAC,GAAG,MAAM;AACzB;;AAGA,MAAa,YAAY;CAAE;CAAY;CAAY;AAAc"}
1
+ {"version":3,"file":"playwright.mjs","names":[],"sources":["../../src/testing/playwright.ts"],"sourcesContent":["/**\n * `foldkit-plus/testing/playwright`: what a user sees, asserted on a running\n * page. A write shows before the server answers, holds still until it is\n * answered, and stays after; a step never shows a given text, at any moment;\n * the page logs no error.\n *\n * Each checks the page as drawn, over the real network: it proves that the\n * whole application (server, hydration, persistence, the Worker) delivers a\n * property. Which Message breaks a read's property is\n * `foldkit-plus/remote/testing`'s `Trace`, which records every Model without\n * a browser; reach for it once one of these fails.\n *\n * Playwright is an optional peer of `foldkit-plus`, needed only for its types:\n * this module calls nothing but the `Page` it is given.\n */\nimport { Duration, Option, Schema } from 'effect'\nimport { RemoteJsonRequest } from 'foldkit-remote'\nimport type { ConsoleMessage, Locator, Page, Request, Route } from 'playwright'\n\nconst decodeRequest = Schema.decodeUnknownOption(Schema.fromJsonString(RemoteJsonRequest))\n\n/** The operation of a Remote request over HTTP, by the JSON request `Remote.http` sends. */\nconst remoteOperation = (request: Request): Option.Option<RemoteJsonRequest['operation']> => {\n const body = request.method() === 'POST' ? request.postData() : null\n return body === null ? Option.none() : Option.map(decodeRequest(body), sent => sent.operation)\n}\n\nconst isRemoteMutation = (request: Request): boolean =>\n Option.contains(remoteOperation(request), 'mutate')\n\nconst millis = (input: Duration.Input) => Duration.toMillis(Duration.fromInputUnsafe(input))\n\n/**\n * How long `act` may take at least before it is taken to wait for its own\n * write's answer. Only that case needs a limit, so it is far longer than a\n * click takes on a loaded runner, whatever `hold` is.\n */\nconst ACT_LIMIT = 10_000\n\n/**\n * Resolves once three frames in a row pass with no change to the document,\n * or after two seconds of changes: a Message an answer caused has been drawn.\n */\nconst quiet = (page: Page): Promise<void> =>\n page.evaluate(\n () =>\n new Promise<void>(resolve => {\n let calm = 0\n const observer = new MutationObserver(() => {\n calm = 0\n })\n const done = () => {\n observer.disconnect()\n resolve()\n }\n observer.observe(document, {\n childList: true,\n subtree: true,\n characterData: true,\n attributes: true,\n })\n setTimeout(done, 2000)\n const frame = () => {\n calm += 1\n if (calm >= 3) done()\n else requestAnimationFrame(frame)\n }\n requestAnimationFrame(frame)\n }),\n )\n\n/**\n * Writes that reach the server some way other than `Remote.http` (a port to a\n * SharedWorker, a sandbox in the page). The page holds its own answers (the\n * test opened it so), and `answered` resolves on the page's own evidence that\n * nothing it wrote is pending: an outbox emptied, a status gone.\n */\nexport interface PageWrites {\n readonly answered: () => Promise<unknown>\n}\n\nexport interface OptimisticOptions {\n /** The user's action that writes: a click, a key. */\n readonly act: () => Promise<unknown>\n /** What the page shows once the write is made. */\n readonly shows: Locator\n /**\n * What must hold still from the moment `shows` shows until the write is\n * answered and drawn: `'put'` (the default), each element `shows` resolves\n * to; a `Locator`, what it resolves to instead (the list around a row its\n * answer deliberately draws again); `'shown'`, nothing, so only that\n * `shows` shows again after the answer.\n */\n readonly stays?: 'put' | 'shown' | Locator\n /** How the writes travel: `'http'` (the default), `Remote.http`'s requests, held at the network. */\n readonly writes?: 'http' | PageWrites\n /**\n * How long each Remote mutation is held at the network at least: it is held\n * on until `act` has ended and `shows` has been looked for. `'3 seconds'`\n * unless given.\n */\n readonly hold?: Duration.Input\n /** How soon after `act` begins `shows` must show, while every write is held. `'1 second'` unless given. */\n readonly within?: Duration.Input\n}\n\n/** What the page script needs to keep what it watches apart from another watch's. */\ninterface StillWatch {\n readonly key: string\n}\n\n// Runs in the page over the elements to keep still. A node removed and put\n// back in one batch reads as attached in the callback, so removals and\n// `hidden` are replayed from the records; layout and visibility are sampled\n// every frame, as a reader sees them. Each element reports each kind of fault once.\nconst watchStill = (elements: ReadonlyArray<Element>, { key }: StillWatch): number => {\n const started = performance.now()\n const where = (element: Element) => {\n const box = element.getBoundingClientRect()\n return { x: box.left + window.scrollX, y: box.top + window.scrollY }\n }\n const named = (element: Element) => {\n const html = element.outerHTML.replace(/\\s+/g, ' ')\n return html.length > 80 ? `${html.slice(0, 77)}...` : html\n }\n const watched = elements.map(element => {\n const lineage = new Set<Node>()\n for (let node: Node | null = element; node !== null; node = node.parentNode) lineage.add(node)\n return { element, lineage, first: where(element), faults: new Map<string, string>() }\n })\n const fault = (each: (typeof watched)[number], kind: string, words: string) => {\n if (!each.faults.has(kind))\n each.faults.set(\n kind,\n `${named(each.element)} ${words}, ${Math.round(performance.now() - started)} ms after it showed`,\n )\n }\n const observer = new MutationObserver(records => {\n for (const record of records)\n for (const each of watched) {\n if ([...record.removedNodes].some(node => each.lineage.has(node)))\n fault(each, 'removed', 'was taken out of the page')\n if (\n record.type === 'attributes' &&\n record.attributeName === 'hidden' &&\n record.oldValue === null &&\n each.lineage.has(record.target)\n )\n fault(each, 'hidden', 'was hidden')\n }\n for (const each of watched)\n if (each.faults.has('removed') && each.element.isConnected)\n fault(each, 'moved', 'was taken out and put back')\n })\n observer.observe(document, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: ['hidden'],\n attributeOldValue: true,\n })\n let frame = 0\n const sample = () => {\n for (const each of watched) {\n if (!each.element.isConnected) continue\n if (!each.element.checkVisibility({ visibilityProperty: true }))\n fault(each, 'hidden', 'was hidden')\n const now = where(each.element)\n const dx = now.x - each.first.x\n const dy = now.y - each.first.y\n const away = [\n ...(Math.abs(dx) > 1 ? [`${Math.round(Math.abs(dx))}px ${dx < 0 ? 'left' : 'right'}`] : []),\n ...(Math.abs(dy) > 1 ? [`${Math.round(Math.abs(dy))}px ${dy < 0 ? 'up' : 'down'}`] : []),\n ]\n if (away.length > 0) fault(each, 'shifted', `moved ${away.join(' and ')}`)\n }\n frame = requestAnimationFrame(sample)\n }\n sample()\n Reflect.set(window, key, () => {\n Reflect.deleteProperty(window, key)\n observer.disconnect()\n cancelAnimationFrame(frame)\n return watched.map(each => ({\n element: each.element,\n name: named(each.element),\n faults: each.faults,\n }))\n })\n return elements.length\n}\n\n/**\n * Stops the watch and lists what went wrong. `now` is what the locator\n * resolves to once settled: a watched element gone from the page while one\n * that was not watched stands there was replaced, not only removed.\n */\nconst stopStill = (now: ReadonlyArray<Element>, { key }: StillWatch): ReadonlyArray<string> => {\n const report: ReadonlyArray<{\n readonly element: Element\n readonly name: string\n readonly faults: ReadonlyMap<string, string>\n }> = Reflect.apply(Reflect.get(window, key), undefined, [])\n const newcomer = now.some(element => !report.some(each => each.element === element))\n return report.flatMap(each => {\n const replaced = newcomer && !each.element.isConnected\n return [\n ...[...each.faults].flatMap(([kind, words]) =>\n replaced && kind === 'removed' ? [] : [words],\n ),\n ...(replaced ? [`${each.name} was replaced by a new element`] : []),\n ]\n })\n}\n\nconst stopIfWatching = ({ key }: StillWatch) => {\n const stop: unknown = Reflect.get(window, key)\n if (typeof stop === 'function') stop()\n}\n\n/**\n * The write shows before the server answers, holds still until it has been\n * answered and drawn, and still shows after.\n *\n * Every Remote mutation the page sends is held at the network until `act`\n * has ended and `shows` has been looked for, and for `hold` at least, so\n * what shows was drawn before any answer however long `act` takes;\n * `shows` must be visible within `within` of `act` beginning. From\n * then until settled, what `stays` names must stay in the page as the same\n * nodes, in the same place in their parent, within 1px of where they were\n * drawn, and visible. Settled is evidence, not a wait: no Remote request of\n * the page in flight (an answer can lead to more, such as a placed list's\n * first page under `verifyPredictions`), or `writes.answered`, then the page\n * quiet for three frames. An error the page logs meanwhile fails it too: a\n * `PredictionMismatch` is logged as one. Throws otherwise, when `act` sent\n * no Remote mutation over HTTP, since nothing was then held, and when `act`\n * has not ended 10 seconds (or `hold`, if longer) after it began: one that\n * waits for its own write's answer would wait for good.\n */\nconst optimistic = async (page: Page, options: OptimisticOptions): Promise<void> => {\n const writes = options.writes ?? 'http'\n const hold = millis(options.hold ?? '3 seconds')\n const within = millis(options.within ?? '1 second')\n // Opened once `shows` has been looked for and is watched: no write is\n // answered before, so nothing shown by then is an answer.\n let release = () => {}\n const looked = new Promise<void>(resolve => {\n release = resolve\n })\n const held: Array<Promise<void>> = []\n // Every Remote request from `act` on that is not yet answered.\n const inFlight = new Set<Request>()\n const sent = (request: Request) => {\n if (Option.isSome(remoteOperation(request))) inFlight.add(request)\n }\n // How many have been answered: a quiet that began before the last answer\n // may have ended before the page drew it.\n let answers = 0\n const done = (request: Request) => {\n if (inFlight.delete(request)) answers += 1\n }\n const errors: Array<string> = []\n const logged = (message: ConsoleMessage) => {\n if (message.type() === 'error') errors.push(message.text())\n }\n const thrown = (error: Error) => errors.push(String(error))\n // Let through after `hold`, once looked. The answer is awaited apart from the\n // handler: Playwright passes a request on to the next handler only once this one returns.\n const letThrough = async (route: Route) => {\n await Promise.all([new Promise(resume => setTimeout(resume, hold)), looked])\n await route.fallback()\n }\n const answered = async (request: Request) => {\n const response = await request.response()\n if (response !== null) await response.finished()\n }\n const route = await page.route('**/*', (route, request) => {\n if (writes !== 'http' || !isRemoteMutation(request)) return route.fallback()\n held.push(answered(request))\n return letThrough(route)\n })\n page.on('request', sent)\n page.on('requestfinished', done)\n page.on('requestfailed', done)\n page.on('console', logged)\n page.on('pageerror', thrown)\n const shows = String(options.shows)\n const stays = options.stays ?? 'put'\n const watched =\n stays === 'shown'\n ? Option.none<Locator>()\n : Option.some(stays === 'put' ? options.shows : stays)\n const watch: StillWatch = { key: `__foldkitStill${crypto.randomUUID().replaceAll('-', '')}` }\n let overdue: ReturnType<typeof setTimeout> | undefined\n try {\n const shown = options.shows.waitFor({ state: 'visible', timeout: within }).then(\n () => Option.none<unknown>(),\n (error: unknown) => Option.some(error),\n )\n const acted = Promise.resolve().then(options.act)\n // An action waiting for its own write's answer would wait for good.\n const deadline =\n writes === 'http'\n ? new Promise<false>(resolve => {\n overdue = setTimeout(resolve, Math.max(hold, ACT_LIMIT), false)\n })\n : new Promise<never>(() => {})\n const ended = await Promise.race([acted.then(() => true), deadline])\n if (!ended) {\n release()\n // The action is left running, so its eventual outcome is unobserved\n // here: a rejection after the deadline must not surface as an\n // unhandled rejection.\n void acted.catch(() => {})\n throw new Error(\n `optimistic: the action did not end within ${Math.max(hold, ACT_LIMIT)} ms, and every write is held until it does: does it wait for its own write's answer?`,\n )\n }\n const missed = await shown\n if (Option.isSome(missed))\n throw new Error(`optimistic: ${shows} did not show within ${within} ms of the action`, {\n cause: missed.value,\n })\n if (Option.isSome(watched) && (await watched.value.evaluateAll(watchStill, watch)) === 0)\n throw new Error(`optimistic: ${String(watched.value)}, what stays, matches nothing`)\n release()\n if (writes === 'http') {\n if (held.length === 0)\n throw new Error(`optimistic: ${shows} showed, but the action sent no Remote mutation`)\n } else {\n await writes.answered()\n }\n // Every held write is in flight until answered, and an answer drawn can ask\n // for more: settled once the page asks nothing and stays quiet from after\n // the last answer. The network finishes before the page reads the answer,\n // and an app draws it on a later frame.\n for (;;) {\n const before = answers\n await quiet(page)\n if (inFlight.size === 0 && answers === before) break\n }\n if (Option.isSome(watched)) {\n const faults = await watched.value.evaluateAll(stopStill, watch)\n if (faults.length > 0)\n throw new Error(\n `optimistic: ${String(watched.value)} did not hold still until the write settled:\\n ${faults.join('\\n ')}`,\n )\n }\n if (!(await options.shows.isVisible()))\n throw new Error(\n `optimistic: ${shows} showed while the write was held, but not after its answer`,\n )\n if (errors.length > 0)\n throw new Error(\n `optimistic: the page logged an error while the write settled:\\n ${errors.join('\\n ')}`,\n )\n } finally {\n clearTimeout(overdue)\n release()\n // A check that failed before reading the watch leaves it sampling every frame.\n if (!page.isClosed()) await page.evaluate(stopIfWatching, watch)\n page.off('request', sent)\n page.off('requestfinished', done)\n page.off('requestfailed', done)\n page.off('console', logged)\n page.off('pageerror', thrown)\n await route.dispose()\n await Promise.allSettled(held)\n }\n}\n\nexport interface NeverShowsOptions {\n /** What the page must not show at any moment of `during`. */\n readonly text: string | RegExp\n /**\n * The steps to watch: a reload, a navigation away and back. End it on what\n * the page waits for (an answer, a row), since watching stops once it ends\n * and the page is quiet.\n */\n readonly during: () => Promise<unknown>\n}\n\n/** What the page script needs: the binding to report through, and the text as a pattern. */\ninterface Watch {\n readonly key: string\n readonly source: string\n readonly flags: string\n}\n\n// Runs in the page, in the open document and in each one loaded after: after\n// every change to the document, the rendered text (`innerText` leaves hidden\n// text out) is searched, so a text shown for one frame is seen, not sampled.\nconst watchText = ({ key, source, flags }: Watch) => {\n if (window !== window.top) return\n const pattern = new RegExp(source, flags)\n let reported = false\n const check = () => {\n if (reported) return\n const line = (document.body?.innerText ?? '').split('\\n').find(each => pattern.test(each))\n if (line === undefined) return\n reported = true\n Reflect.apply(Reflect.get(window, key), undefined, [line])\n }\n const observer = new MutationObserver(check)\n observer.observe(document, {\n childList: true,\n subtree: true,\n characterData: true,\n attributes: true,\n })\n Reflect.set(window, `${key}Stop`, () => observer.disconnect())\n check()\n}\n\nconst stopWatching = (key: string) =>\n Reflect.apply(Reflect.get(window, `${key}Stop`), undefined, [])\n\n/**\n * The page never shows `text` while `during` runs, nor until the page is\n * quiet after it: a cached page revisited never reads \"Loading…\", even for\n * one frame. Throws with the line that showed.\n */\nconst neverShows = async (page: Page, options: NeverShowsOptions): Promise<void> => {\n const key = `__foldkitNeverShows${crypto.randomUUID().replaceAll('-', '')}`\n const { text } = options\n const watch: Watch =\n typeof text === 'string'\n ? { key, source: text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'), flags: '' }\n : { key, source: text.source, flags: text.flags }\n const shown: Array<string> = []\n const binding = await page.exposeBinding(key, (_, line: string) => {\n shown.push(line)\n })\n const script = await page.addInitScript(watchText, watch)\n try {\n await page.evaluate(watchText, watch)\n await options.during()\n await quiet(page)\n } finally {\n await script.dispose()\n if (!page.isClosed()) await page.evaluate(stopWatching, key)\n await binding.dispose()\n }\n if (shown.length > 0)\n throw new Error(`neverShows: the page showed ${String(text)}: \"${shown[0]}\"`)\n}\n\n/**\n * Collects every error the page logs (`console.error`) and every exception it\n * does not catch, from now until the page closes. Read the list at the end.\n */\nconst consoleErrors = (page: Page): (() => ReadonlyArray<string>) => {\n const errors: Array<string> = []\n page.on('console', message => {\n if (message.type() === 'error') errors.push(message.text())\n })\n page.on('pageerror', error => errors.push(String(error)))\n return () => [...errors]\n}\n\n/** Assertions on what a running page shows, for Playwright. */\nexport const Behaviors = { optimistic, neverShows, consoleErrors } as const\n"],"mappings":";;;;;;;;;;;;;;;;;;AAmBA,MAAM,gBAAgB,OAAO,oBAAoB,OAAO,eAAe,iBAAiB,CAAC;;AAGzF,MAAM,mBAAmB,YAAoE;CAC3F,MAAM,OAAO,QAAQ,OAAO,MAAM,SAAS,QAAQ,SAAS,IAAI;CAChE,OAAO,SAAS,OAAO,O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AMA,MAAM,iBAAiB,SAA8C;CACnE,MAAM,SAAwB,CAAC;CAC/B,KAAK,GAAG,YAAW,YAAW;EAC5B,IAAI,QAAQ,KAAK,MAAM,SAAS,OAAO,KAAK,QAAQ,KAAK,CAAC;CAC5D,CAAC;CACD,KAAK,GAAG,cAAa,UAAS,OAAO,KAAK,OAAO,KAAK,CAAC,CAAC;CACxD,aAAa,CAAC,GAAG,MAAM;AACzB;;AAGA,MAAa,YAAY;CAAE;CAAY;CAAY;AAAc"}
@@ -121,13 +121,21 @@ export interface CpuReading {
121
121
  readonly status: number;
122
122
  /** The route's first request in this call: in a fresh stack, a cold isolate's. */
123
123
  readonly cold: number;
124
- /** The mean of the requests after the first. */
124
+ /**
125
+ * The most a request after the first spent, in milliseconds. A deployed
126
+ * Worker's limit applies to each request, not to their mean.
127
+ */
125
128
  readonly warm: number;
126
129
  }
127
130
  export interface CpuBudget {
128
131
  /** The routes, by the name a failure reports them with. */
129
132
  readonly routes: Readonly<Record<string, CpuRoute>>;
130
- /** Milliseconds a warm request may spend. */
133
+ /**
134
+ * Milliseconds each request after the first may spend. A meter's own
135
+ * resolution bounds how small this can be: Windows books a thread's CPU
136
+ * time in 15.6 ms ticks, so a budget near that reads one request's cost
137
+ * as a tick whether it spent it or not.
138
+ */
131
139
  readonly warm: number;
132
140
  /** Milliseconds the first request may spend; unchecked when not given. */
133
141
  readonly cold?: number;
@@ -136,9 +144,10 @@ export interface CpuBudget {
136
144
  }
137
145
  /**
138
146
  * Asks each route once, then `runs` times more, one request at a time, each
139
- * response read in full, and reads what each cost. Throws listing every
140
- * reading when a route spends more than the budget, or answers a 5xx, whose
141
- * cost says nothing of the route's.
147
+ * response read in full, and reads what each cost. Every warm request is
148
+ * checked, since a deployed Worker's limit applies to each rather than to
149
+ * their mean. Throws listing every reading when a route spends more than
150
+ * the budget, or answers a 5xx, whose cost says nothing of the route's.
142
151
  */
143
152
  declare const budget: (meter: CpuMeter, { routes, warm, cold, runs }: CpuBudget) => Promise<ReadonlyArray<CpuReading>>;
144
153
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"workers.d.mts","names":[],"sources":["../../src/testing/workers.ts"],"mappings":";;iBA2CiB;;WAEN;;WAEA;;;;;;WAMA,OAAO,SAAS,mBAAmB;;WAEnC,UAAU,SAAS;;;;;WAKnB,UAAU,cAAc;;;;;;WAMxB;;;;;WAKA;;KAGN,OAAO,SAAS;;iBAGJ;;WAEN;WACA;WACA;;;;;;iBAOM;;WAEN;;;;;;;;WAQA,YAAY;;;;;;WAMZ,YAAY;;iBAGN,MAAM;;WAEZ;;;;;WAKA,WAAW,QAAQ;;WAEnB,UAAU;;;;;;WAMV,YAAY,cAAc;;;;;;;;WAQ1B,KAAK;;;;;;;WAOL,QAAQ,UAAU,kBAAkB;;;;;;;WAOpC,YAAY;;;YAIX,YAAY,KAAK;;iBAGZ;;WAEN;WACA,QAAQ,SAAS,YAAY,QAAQ;;WAErC,aAAa;;;;;;YAOZ,2BAA2B;;iBAGtB;WACN;;WAEA;;WAEA;;WAEA;;iBAGM;;WAEN,QAAQ,SAAS,eAAe;;WAEhC;;WAEA;;WAEA;;;;;;;;cA8IL,SAAM,OACH,YAAQ,QAAA,MAAA,MAAA,QACmB,cACjC,QAAQ,cAAc;;;;;;cA8DnB,WAAQ,SACH,SAAS,YAAY,QAAQ,YAAU,oBAE/C;;;;;;qBAOU;;;;;cAyMP,cAAW,SAAmB,KAAK,sCAAoC;;;;;;cAyBvE,QAAe,KAAG,SAAW,iBAAe,QAAQ,MAAM;;;;;;qBA2PnD"}
1
+ {"version":3,"file":"workers.d.mts","names":[],"sources":["../../src/testing/workers.ts"],"mappings":";;iBA2CiB;;WAEN;;WAEA;;;;;;WAMA,OAAO,SAAS,mBAAmB;;WAEnC,UAAU,SAAS;;;;;WAKnB,UAAU,cAAc;;;;;;WAMxB;;;;;WAKA;;KAGN,OAAO,SAAS;;iBAGJ;;WAEN;WACA;WACA;;;;;;iBAOM;;WAEN;;;;;;;;WAQA,YAAY;;;;;;WAMZ,YAAY;;iBAGN,MAAM;;WAEZ;;;;;WAKA,WAAW,QAAQ;;WAEnB,UAAU;;;;;;WAMV,YAAY,cAAc;;;;;;;;WAQ1B,KAAK;;;;;;;WAOL,QAAQ,UAAU,kBAAkB;;;;;;;WAOpC,YAAY;;;YAIX,YAAY,KAAK;;iBAGZ;;WAEN;WACA,QAAQ,SAAS,YAAY,QAAQ;;WAErC,aAAa;;;;;;YAOZ,2BAA2B;;iBAGtB;WACN;;WAEA;;WAEA;;;;;WAKA;;iBAGM;;WAEN,QAAQ,SAAS,eAAe;;;;;;;WAOhC;;WAEA;;WAEA;;;;;;;;;cA+IL,SAAM,OACH,YAAQ,QAAA,MAAA,MAAA,QACmB,cACjC,QAAQ,cAAc;;;;;;cAoEnB,WAAQ,SACH,SAAS,YAAY,QAAQ,YAAU,oBAE/C;;;;;;qBAOU;;;;;cAyMP,cAAW,SAAmB,KAAK,sCAAoC;;;;;;cAyBvE,QAAe,KAAG,SAAW,iBAAe,QAAQ,MAAM;;;;;;qBA2PnD"}
@@ -120,9 +120,10 @@ const workerdMeter = (origin, dispatch, spawned) => {
120
120
  };
121
121
  /**
122
122
  * Asks each route once, then `runs` times more, one request at a time, each
123
- * response read in full, and reads what each cost. Throws listing every
124
- * reading when a route spends more than the budget, or answers a 5xx, whose
125
- * cost says nothing of the route's.
123
+ * response read in full, and reads what each cost. Every warm request is
124
+ * checked, since a deployed Worker's limit applies to each rather than to
125
+ * their mean. Throws listing every reading when a route spends more than
126
+ * the budget, or answers a 5xx, whose cost says nothing of the route's.
126
127
  */
127
128
  const budget = async (meter, { routes, warm, cold, runs = 5 }) => {
128
129
  if (!Number.isInteger(runs) || runs < 1) throw new Error(`Cpu.budget: runs must be a whole number from 1, not ${runs}.`);
@@ -139,13 +140,19 @@ const budget = async (meter, { routes, warm, cold, runs = 5 }) => {
139
140
  const start = await meter.spent();
140
141
  await ask();
141
142
  const first = await meter.spent();
142
- for (let run = 0; run < runs; run++) await ask();
143
- const end = await meter.spent();
143
+ let warmest = 0;
144
+ let previous = first;
145
+ for (let run = 0; run < runs; run++) {
146
+ await ask();
147
+ const now = await meter.spent();
148
+ warmest = Math.max(warmest, now - previous);
149
+ previous = now;
150
+ }
144
151
  readings.push({
145
152
  route: name,
146
153
  status,
147
154
  cold: first - start,
148
- warm: (end - first) / runs
155
+ warm: warmest
149
156
  });
150
157
  }
151
158
  const over = readings.filter((reading) => reading.warm > warm || cold !== void 0 && reading.cold > cold);
@@ -1 +1 @@
1
- {"version":3,"file":"workers.mjs","names":["watch","watchFile"],"sources":["../../src/testing/workers.ts"],"sourcesContent":["/**\n * `foldkit-plus/testing/workers`: a Worker on a local workerd, configured by\n * its own Wrangler configuration.\n *\n * Wrangler's test harness reads the configuration, so bindings, the\n * compatibility date and flags, `.dev.vars` and D1 migrations mean here what\n * they mean to `wrangler deploy`. This module owns only what Wrangler cannot\n * know: the bundle. esbuild builds the entry with the workspace's source\n * condition into a directory of the stack's own, and the harness runs the\n * configuration with `main` pointed there.\n *\n * `wrangler`, `esbuild` and `@foldkit/vite-plugin` are optional peers of\n * `foldkit-plus`, loaded on the first call; Miniflare is read from Wrangler's\n * own copy, so the date check asks the runtime Wrangler starts.\n */\nimport { Option, Schema } from 'effect'\nimport type {\n BuildContext,\n BuildOptions,\n Loader,\n OnLoadArgs,\n OnLoadResult,\n OutputFile,\n Plugin,\n} from 'esbuild'\nimport type { TestHarness, WorkerHandle } from 'wrangler'\nimport { ChildProcess, spawn } from 'node:child_process'\nimport { subscribe, unsubscribe } from 'node:diagnostics_channel'\nimport { readFileSync, watch as watchFile, type FSWatcher } from 'node:fs'\nimport { mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { createInterface } from 'node:readline'\nimport { createRequire } from 'node:module'\nimport { tmpdir } from 'node:os'\nimport { basename, dirname, extname, join, relative, resolve } from 'node:path'\nimport { peer } from './peer.js'\n\nconst SUBPATH = 'testing/workers'\n\nconst wrangler = () => peer(SUBPATH, 'wrangler', () => import('wrangler'))\nconst esbuild = () => peer(SUBPATH, 'esbuild', () => import('esbuild'))\nconst foldkitVite = () =>\n peer(SUBPATH, '@foldkit/vite-plugin', () => import('@foldkit/vite-plugin'))\n\nexport interface StackOptions {\n /** The Worker's Wrangler configuration (`wrangler.toml`, `.json` or `.jsonc`). */\n readonly wrangler: string\n /** The source esbuild bundles into what `main` names. */\n readonly entry: string\n /**\n * Local values for vars the deployed Worker is given elsewhere. As a\n * function, of the origin the stack answers at: the Worker has them from\n * its first request (`origin => ({ ORIGIN: origin })`).\n */\n readonly vars?: Vars | ((origin: string) => Vars)\n /** Local values for secrets, over any in `.dev.vars`. */\n readonly secrets?: Readonly<Record<string, string>>\n /**\n * esbuild plugins for the bundle, the deploy's and the stack's alike. A\n * module one loads is branded with view identities as one read from disk is.\n */\n readonly plugins?: ReadonlyArray<Plugin>\n /**\n * The Vite root of the page the Worker renders; by default the folder of\n * the Wrangler configuration. Each view is named by its module's path from\n * here, as `@foldkit/vite-plugin` names the page's.\n */\n readonly pageRoot?: string\n /**\n * Whether each line the Worker writes to its console is printed here, by\n * its level, as it arrives (`'print'`, the default). `logs()` keeps them either way.\n */\n readonly console?: 'print' | 'quiet'\n}\n\ntype Vars = Readonly<Record<string, string>>\n\n/** A line the Worker wrote to its console. An `Error` logged carries its stack in `message`. */\nexport interface WorkerLog {\n /** As workerd names it: `debug`, `info`, `log`, `warn` or `error`. */\n readonly level: string\n readonly message: string\n readonly timestamp: number\n}\n\n/**\n * What a watched stack reports after each change to the bundle's sources or\n * to the Wrangler configuration.\n */\nexport interface WatchListener {\n /** The new Worker answers at the same origin, over the same storage. */\n readonly onSwap: () => void\n /**\n * The change was not swapped in, and the Worker running keeps answering\n * over the same storage. It did not build, built no code (as an entry saved\n * in place reads for a moment), did not start when tried on a workerd of\n * its own, or is a configuration the stack refuses. Or it was swapped in,\n * and a D1 migration then failed on the running database; the message says so.\n */\n readonly onRefused: (message: string) => void\n /**\n * A Worker that started when tried did not start in the stack. Wrangler's\n * harness tears its runtime down with it, storage included, so the stack\n * has stopped answering and watches no more: call `stop`, and start again.\n */\n readonly onStopped: (message: string) => void\n}\n\nexport interface Stack<Env> {\n /** Where the Worker answers over real HTTP. */\n readonly origin: string\n /**\n * The Worker's bindings, as the Worker sees them. A swap retires the ones\n * read before it (Miniflare's \"poisoned stub\"), so read them after.\n */\n readonly env: () => Promise<Env>\n /** A request straight to the Worker; an upgrade answers with its socket. */\n readonly dispatch: WorkerHandle['fetch']\n /**\n * Takes what the Worker wrote to its console since the last call, oldest\n * first. The lines come from workerd beside the response, not on it, so a\n * line written for a request may arrive after it: poll.\n */\n readonly logs: () => ReadonlyArray<WorkerLog>\n /**\n * Requests sent straight to the Worker, metered for `Cpu.budget` by how\n * long workerd's main thread runs, read from the operating system since\n * workerd reports no CPU (Linux and Windows). That counts the Worker's code\n * and what workerd does on the thread around it, D1's SQLite included,\n * which a deployed Worker's CPU time leaves out.\n */\n readonly cpu: CpuMeter\n /**\n * Rebuilds on every change to a file the bundle read, and rereads the\n * Wrangler configuration when it changes. Each change is first started on\n * a workerd of its own, then swapped in at the same origin, and the D1\n * migrations not yet applied are applied. D1, R2 and Durable Object storage stay.\n */\n readonly watch: (listener: WatchListener) => Promise<void>\n /**\n * Stops watching, stops workerd and removes the bundle's directory, each\n * even when one before it failed. A change not yet being tried swaps\n * nothing and reports nothing; one being tried finishes first. A second\n * call returns the first one's promise.\n */\n readonly stop: () => Promise<void>\n}\n\n/** What a meter answers: a `Response`, or Miniflare's own. */\nexport type CpuAnswer = Pick<Response, 'status' | 'arrayBuffer'>\n\n/** Answers requests, and reads how much CPU time the code answering them has spent. */\nexport interface CpuMeter {\n /** What a route given as a path is resolved against. */\n readonly origin: string\n readonly fetch: (request: Request) => Promise<CpuAnswer>\n /** Milliseconds of CPU time spent so far, from a fixed point of the meter's own. */\n readonly spent: () => Promise<number>\n}\n\n/**\n * A route `Cpu.budget` asks: a path or URL to `GET`, or a function making\n * a new request for each run, since a request's body is read once.\n */\nexport type CpuRoute = string | (() => Request)\n\n/** What one route cost, in milliseconds of CPU time. */\nexport interface CpuReading {\n readonly route: string\n /** The last response's status. */\n readonly status: number\n /** The route's first request in this call: in a fresh stack, a cold isolate's. */\n readonly cold: number\n /** The mean of the requests after the first. */\n readonly warm: number\n}\n\nexport interface CpuBudget {\n /** The routes, by the name a failure reports them with. */\n readonly routes: Readonly<Record<string, CpuRoute>>\n /** Milliseconds a warm request may spend. */\n readonly warm: number\n /** Milliseconds the first request may spend; unchecked when not given. */\n readonly cold?: number\n /** Requests after the first, each answered in full before the next; default 5. */\n readonly runs?: number\n}\n\n/** The processes spawned while a stack's harness starts or reloads; workerd among them. */\ninterface Spawned {\n readonly processes: Array<ChildProcess>\n /** Another stack spawned at the same time, so whose process is whose is unknown. */\n shared: boolean\n}\n\nconst collecting = new Set<Spawned>()\n\n// Named once spawned: Node publishes a process before it starts it.\nconst isWorkerd = (child: ChildProcess) =>\n typeof child.spawnfile === 'string' && /^workerd(\\.exe)?$/.test(basename(child.spawnfile))\n\n// Node publishes every `spawn` here, workerd's by Miniflare included; the\n// harness offers no other way to find the process.\nconst onSpawn = (message: unknown) => {\n if (typeof message !== 'object' || message === null || !('process' in message)) return\n const child = message.process\n if (!(child instanceof ChildProcess)) return\n for (const spawned of collecting) spawned.processes.push(child)\n}\n\n/** Runs `step`, adding the processes it spawns to `into`. */\nconst collect = async <A>(into: Spawned, step: () => Promise<A>): Promise<A> => {\n if (collecting.size === 0) subscribe('child_process', onSpawn)\n for (const other of collecting) other.shared = into.shared = true\n collecting.add(into)\n try {\n return await step()\n } finally {\n collecting.delete(into)\n if (collecting.size === 0) unsubscribe('child_process', onSpawn)\n }\n}\n\nconst isRunning = (child: ChildProcess) => child.exitCode === null && child.signalCode === null\n\n/** Milliseconds a Linux process's main thread has run, by the scheduler's nanoseconds. */\nconst linuxTime = async (pid: number): Promise<number> =>\n Number((await readFile(`/proc/${pid}/task/${pid}/schedstat`, 'utf8')).split(' ')[0]) / 1e6\n\n/**\n * Reads how long processes' main threads have run, where workerd runs\n * JavaScript. V8's helper threads, which collect garbage and compile beside\n * it, are left out: on a server-rendered page they added half as much again.\n */\ninterface CpuReader {\n readonly read: (pids: ReadonlyArray<number>) => Promise<number>\n readonly close: () => void\n}\n\nconst linuxReader = (): CpuReader => ({\n read: async pids => (await Promise.all(pids.map(linuxTime))).reduce((a, b) => a + b, 0),\n close: () => {},\n})\n\n/**\n * Windows has no `/proc`, and Node no call for another process's times, so\n * one PowerShell kept open answers each read: started per read, it takes\n * longer than the requests it measures. The main thread is the one that\n * started first. Windows adds to a thread's time a scheduler tick (15.6 ms)\n * at a time.\n */\nconst windowsReader = (): CpuReader => {\n const shell = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', '-'], {\n stdio: ['pipe', 'pipe', 'ignore'],\n windowsHide: true,\n })\n const waiting: Array<(line: Option.Option<string>) => void> = []\n createInterface({ input: shell.stdout }).on('line', line => waiting.shift()?.(Option.some(line)))\n // A shell that could not start, or ended, answers no read waiting on it.\n const ended = () => waiting.splice(0).forEach(answer => answer(Option.none()))\n shell.on('error', ended).on('exit', ended)\n return {\n read: pids =>\n new Promise((resolve, reject) => {\n waiting.push(line => {\n const ticks = Number(Option.getOrElse(line, () => ''))\n if (Option.isSome(line) && Number.isFinite(ticks)) resolve(ticks / 1e4)\n else\n reject(\n new Error(\n `workerd's CPU time could not be read: ${Option.getOrElse(line, () => 'PowerShell ended')}`,\n ),\n )\n })\n shell.stdin.write(\n `try { (@(${pids.join(',')}) | % { ([Diagnostics.Process]::GetProcessById($_).Threads | Sort-Object StartTime | Select-Object -First 1).TotalProcessorTime.Ticks } | Measure-Object -Sum).Sum } catch { \"$_\" }\\n`,\n )\n }),\n close: () => shell.kill(),\n }\n}\n\nconst readerFor = (): CpuReader => {\n if (process.platform === 'linux') return linuxReader()\n if (process.platform === 'win32') return windowsReader()\n throw new Error(\n `The stack reads workerd's CPU time on Linux and Windows, not ${process.platform}.`,\n )\n}\n\n/** The CPU meter over a stack's workerd processes, its reader made on the first read. */\nconst workerdMeter = (origin: string, dispatch: WorkerHandle['fetch'], spawned: Spawned) => {\n let reader = Option.none<CpuReader>()\n const meter: CpuMeter = {\n origin,\n // Straight to the Worker: over `origin` a second workerd, which proxies\n // what the harness serves, would spend time of its own on every request.\n fetch: async request =>\n dispatch(request.url, {\n method: request.method,\n headers: [...request.headers],\n ...(request.body === null ? {} : { body: await request.arrayBuffer() }),\n }),\n spent: async () => {\n if (spawned.shared)\n throw new Error(\n 'Another stack started in this process while this one did, so whose workerd is ' +\n \"whose is unknown: start stacks one at a time to read a stack's CPU.\",\n )\n const current = Option.getOrElse(reader, readerFor)\n reader = Option.some(current)\n return current.read(\n spawned.processes\n .filter(child => isWorkerd(child) && isRunning(child))\n .flatMap(child => (child.pid === undefined ? [] : [child.pid])),\n )\n },\n }\n return { meter, close: () => Option.map(reader, open => open.close()) }\n}\n\n/**\n * Asks each route once, then `runs` times more, one request at a time, each\n * response read in full, and reads what each cost. Throws listing every\n * reading when a route spends more than the budget, or answers a 5xx, whose\n * cost says nothing of the route's.\n */\nconst budget = async (\n meter: CpuMeter,\n { routes, warm, cold, runs = 5 }: CpuBudget,\n): Promise<ReadonlyArray<CpuReading>> => {\n if (!Number.isInteger(runs) || runs < 1)\n throw new Error(`Cpu.budget: runs must be a whole number from 1, not ${runs}.`)\n const requestOf = (route: CpuRoute) =>\n typeof route === 'string' ? new Request(new URL(route, meter.origin)) : route()\n const readings: Array<CpuReading> = []\n for (const [name, route] of Object.entries(routes)) {\n let status = 0\n const ask = async () => {\n const response = await meter.fetch(requestOf(route))\n await response.arrayBuffer()\n status = response.status\n if (status >= 500) throw new Error(`Cpu.budget: ${name} answered ${status}.`)\n }\n const start = await meter.spent()\n await ask()\n const first = await meter.spent()\n for (let run = 0; run < runs; run++) await ask()\n const end = await meter.spent()\n readings.push({ route: name, status, cold: first - start, warm: (end - first) / runs })\n }\n const over = readings.filter(\n reading => reading.warm > warm || (cold !== undefined && reading.cold > cold),\n )\n if (over.length > 0)\n throw new Error(\n `Over the CPU budget (warm ${warm} ms${cold === undefined ? '' : `, cold ${cold} ms`}): ` +\n `${over.map(reading => reading.route).join(', ')}\\n` +\n readings\n .map(\n reading =>\n ` ${reading.route}: cold ${reading.cold.toFixed(2)} ms, ` +\n `warm ${reading.warm.toFixed(2)} ms (status ${reading.status})`,\n )\n .join('\\n'),\n )\n return readings\n}\n\nconst pause = new Int32Array(new SharedArrayBuffer(4))\n\n/**\n * Milliseconds this thread has run. Linux books a running thread's time at\n * each scheduler tick (4 ms at 250 Hz), and `threadCpuUsage` reads that\n * book; a millisecond's sleep has the scheduler book the rest, and its own\n * count is in nanoseconds. Read synchronously, so on this thread rather\n * than the pool's.\n */\nconst threadTime = (): number => {\n if (process.platform === 'linux') {\n Atomics.wait(pause, 0, 0, 1)\n return Number(readFileSync('/proc/thread-self/schedstat', 'utf8').split(' ')[0]) / 1e6\n }\n const { user, system } = process.threadCpuUsage()\n return (user + system) / 1000\n}\n\n/**\n * A meter over `answer` run in this process, by this thread's CPU time: for\n * a Worker's handler Node can run (no D1 or other binding of workerd's),\n * whose work happens on the thread that awaits it.\n */\nconst inThread = (\n answer: (request: Request) => Promise<CpuAnswer>,\n origin = 'http://localhost',\n): CpuMeter => ({ origin, fetch: answer, spent: async () => threadTime() })\n\n/**\n * What a request costs in CPU time, which Miniflare neither limits nor\n * reports, while a deployed Worker fails past its plan's limit (error 1102).\n * `Cpu.budget` reads routes through a meter: a stack's `cpu`, or `Cpu.inThread`.\n */\nexport const Cpu = { budget, inThread } as const\n\n/**\n * The part of the configuration the stack reads itself. Wrangler validates\n * the whole of it when the harness loads it.\n */\nconst Config = Schema.Struct({\n main: Schema.String,\n compatibility_date: Schema.String,\n // The stack bundles; Wrangler bundling `main` again would deploy other code.\n no_bundle: Schema.Literal(true),\n d1_databases: Schema.optional(Schema.Array(Schema.Struct({ binding: Schema.String }))),\n})\n\n/**\n * The newest date the workerd Wrangler starts supports, from Wrangler's own\n * Miniflare: an application's own `miniflare` may be another release. Call it\n * after `wrangler()`, which says so when Wrangler is missing.\n */\nconst supportedDate = (): string => {\n const fromWrangler = createRequire(createRequire(import.meta.url).resolve('wrangler'))\n return Schema.decodeUnknownSync(Schema.Struct({ supportedCompatibilityDate: Schema.String }))(\n fromWrangler('miniflare'),\n ).supportedCompatibilityDate\n}\n\nconst readConfig = async (path: string) => {\n const { experimental_readRawConfig } = await wrangler()\n const { rawConfig: raw } = experimental_readRawConfig({ config: path })\n if ('env' in raw)\n throw new Error(`${path}: the local stack runs the top-level Worker; [env.*] is not read.`)\n const config = Schema.decodeUnknownSync(Config)(raw)\n // Miniflare would run a date it does not know at its own latest, with a\n // warning nobody reads, and the tests would pass on a runtime the deploy does not get.\n const supported = supportedDate()\n if (config.compatibility_date > supported)\n throw new Error(\n `${path} asks for compatibility_date ${config.compatibility_date}, but the installed ` +\n `workerd supports up to ${supported}. Move wrangler to a release that knows it.`,\n )\n return { raw, config }\n}\n\n// The modules Vite's view-identity transform reads, and the loader each is read with.\nconst scriptLoaders: Readonly<Record<string, Loader>> = {\n '.ts': 'ts',\n '.mts': 'ts',\n '.tsx': 'tsx',\n '.js': 'js',\n '.mjs': 'js',\n '.jsx': 'jsx',\n}\nconst SCRIPT = /\\.(?:ts|tsx|js|jsx|mts|mjs)$/\nconst scripts = new Set(Object.values(scriptLoaders))\n// Vite skips installed packages: Foldkit's own, whose brand would stamp every vnode as it is made.\nconst isPackaged = (path: string) => /[\\\\/]node_modules[\\\\/]/.test(path)\n\n/**\n * The plugins, with the Worker's views branded as `@foldkit/vite-plugin`\n * brands the page's build: each function's result named by its module's path\n * from `root`. Foldkit adopts a served element only where that name is the\n * one the browser's view gives it; unbranded, the Worker's page was rebuilt on\n * every hydration, silently in production (#412).\n *\n * Vite brands what any load returns, but esbuild takes the first `onLoad`\n * that answers, so each plugin's is wrapped and a module it loads (with\n * `pnpm mutate`'s edits, say) is branded too. `foldkit/brand` resolves from\n * `root`, as the page's does; a root that resolves none has no Foldkit page\n * to match, and the Worker is bundled as written.\n */\nconst viewIdentity = (root: string, plugins: ReadonlyArray<Plugin>): Array<Plugin> => {\n // Found at each build's start, so a watched stack sees Foldkit installed.\n let brand = Option.none<string>()\n const resolving = Symbol('foldkit/brand')\n const brands = ({ path, namespace }: OnLoadArgs) =>\n Option.isSome(brand) && namespace === 'file' && SCRIPT.test(path) && !isPackaged(path)\n /** `contents` branded, or none where nothing in them returns. */\n const branded = async (\n contents: string | Uint8Array,\n loader: Loader,\n path: string,\n ): Promise<Option.Option<string>> => {\n const { transform } = await esbuild()\n const { transformViewIdentity } = await foldkitVite()\n // The brand reads JavaScript, as Vite hands it over after its own TypeScript pass.\n const { code } = await transform(contents, { loader, sourcefile: path })\n return Option.fromNullOr(transformViewIdentity(code, path, root)).pipe(\n Option.map(result => result.code),\n )\n }\n const brandedResult = async (result: OnLoadResult, args: OnLoadArgs): Promise<OnLoadResult> => {\n const loader = result.loader ?? scriptLoaders[extname(args.path)]\n const { contents } = result\n if (!brands(args) || contents === undefined || loader === undefined || !scripts.has(loader))\n return result\n return Option.match(await branded(contents, loader, args.path), {\n onNone: () => result,\n onSome: contents => ({ ...result, contents, loader: 'js' }),\n })\n }\n const wrapped = (plugin: Plugin): Plugin => ({\n ...plugin,\n setup: build =>\n plugin.setup({\n ...build,\n onLoad: (options, load) =>\n build.onLoad(options, async args => {\n const result = await load(args)\n return result === null || result === undefined ? result : brandedResult(result, args)\n }),\n }),\n })\n return [\n {\n name: 'foldkit-view-identity',\n setup: build => {\n build.onStart(async () => {\n const found = await build.resolve('foldkit/brand', {\n kind: 'import-statement',\n resolveDir: root,\n pluginData: resolving,\n })\n brand = found.errors.length === 0 ? Option.some(found.path) : Option.none()\n })\n build.onResolve({ filter: /^foldkit\\/brand$/ }, args =>\n args.pluginData === resolving\n ? undefined\n : Option.match(brand, { onNone: () => undefined, onSome: path => ({ path }) }),\n )\n },\n },\n ...plugins.map(wrapped),\n {\n // Last: a module no plugin loaded, read from disk.\n name: 'foldkit-view-identity-load',\n setup: build =>\n build.onLoad({ filter: SCRIPT }, async args => {\n const loader = scriptLoaders[extname(args.path)]\n if (!brands(args) || loader === undefined) return undefined\n const code = await branded(await readFile(args.path), loader, args.path)\n return Option.match(code, {\n onNone: () => undefined,\n onSome: contents => ({ contents, loader: 'js' as const }),\n })\n }),\n },\n ]\n}\n\n/**\n * How the entry is bundled, for the stack and for `wrangler deploy`: the\n * script at `outfile`, and beside it any `.wasm` it imports, which `no_bundle`\n * Wrangler loads as a compiled module. `node:*` stays external for\n * `nodejs_compat`.\n */\nconst bundleOptions = (options: StackOptions, outfile: string) =>\n ({\n entryPoints: [options.entry],\n bundle: true,\n format: 'esm',\n platform: 'browser',\n conditions: ['foldkit-plus:source'],\n external: ['cloudflare:workers', 'node:*'],\n loader: { '.wasm': 'copy' },\n plugins: viewIdentity(\n resolve(options.pageRoot ?? dirname(options.wrangler)),\n options.plugins ?? [],\n ),\n outdir: dirname(outfile),\n entryNames: basename(outfile, '.js'),\n write: false,\n logLevel: 'silent',\n }) satisfies BuildOptions\n\ntype OutputFiles = ReadonlyArray<OutputFile>\n\nconst writeOutputs = async (\n files: ReadonlyArray<{ readonly path: string; readonly contents: Uint8Array }>,\n) => {\n for (const file of files) {\n await mkdir(dirname(file.path), { recursive: true })\n await writeFile(file.path, file.contents)\n }\n}\n\nconst identityOf = (files: OutputFiles) => files.map(file => `${file.path}:${file.hash}`).join()\n\n/** Node's console method for each level workerd writes; any other prints as a log. */\nconst printers = new Map<string, (line: string) => void>([\n ['debug', line => console.debug(line)],\n ['info', line => console.info(line)],\n ['warn', line => console.warn(line)],\n ['error', line => console.error(line)],\n])\n\nconst print = (log: WorkerLog) =>\n (printers.get(log.level) ?? (line => console.log(line)))(`[worker] ${log.message}`)\n\nconst errorText = (error: unknown) => (error instanceof Error ? error.message : String(error))\n\n/** Writes the bundle where `main` says, for `wrangler deploy`. */\nconst writeBundle = async (options: Omit<StackOptions, 'vars' | 'secrets'>): Promise<void> => {\n const { config } = await readConfig(options.wrangler)\n const outfile = resolve(dirname(options.wrangler), config.main)\n const { build } = await esbuild()\n await writeOutputs((await build(bundleOptions(options, outfile))).outputFiles)\n}\n\ntype Raw = Awaited<ReturnType<typeof readConfig>>['raw']\n\n/** What the stack runs: a configuration and a bundle, swapped in together. */\ninterface Running {\n readonly raw: Raw\n readonly config: typeof Config.Type\n readonly files: OutputFiles\n}\n\nconst migrate = async (worker: WorkerHandle, config: typeof Config.Type) => {\n for (const database of config.d1_databases ?? []) await worker.applyD1Migrations(database.binding)\n}\n\n/**\n * Starts the Worker with a fresh, migrated D1 for each `[[d1_databases]]`,\n * and empty R2 and Durable Object storage. Each call is a stack of its own,\n * so test files running side by side share nothing.\n */\nconst start = async <Env>(options: StackOptions): Promise<Stack<Env>> => {\n const { raw, config } = await readConfig(options.wrangler)\n const { build, context } = await esbuild()\n const { createTestHarness } = await wrangler()\n const directory = join(tmpdir(), `foldkit-workers-${crypto.randomUUID()}`)\n const outfile = join(directory, basename(config.main))\n // Where a change is started on a workerd of its own before the swap.\n const trialDirectory = join(directory, 'trial')\n const bundle = bundleOptions(options, outfile)\n // In memory: a source that does not build fails here, before anything exists to clean up.\n const first = (await build(bundle)).outputFiles\n\n const optionsFor = (raw: Raw, main: string, vars: Vars | undefined) => ({\n root: dirname(options.wrangler),\n workers: [{ config: { ...raw, main }, vars, secrets: options.secrets }],\n })\n const given = options.vars\n // Given here, or once the stack knows its origin.\n let vars = typeof given === 'function' ? undefined : given\n const harness: TestHarness = createTestHarness(optionsFor(raw, outfile, vars))\n const spawned: Spawned = { processes: [], shared: false }\n // Where a trial's workerd goes: collected only so that a stack starting beside it knows.\n const trials: Spawned = { processes: [], shared: false }\n let closeMeter = () => {}\n // The harness keeps workerd's console and offers no handler, so it is drained:\n // read and cleared in one synchronous step, nothing is read twice or missed.\n const kept: Array<WorkerLog> = []\n const drain = () => {\n const fresh = harness.getLogs()\n harness.clearLogs()\n if (options.console !== 'quiet') fresh.forEach(print)\n kept.push(...fresh)\n }\n const draining = setInterval(drain, 100)\n draining.unref()\n let watching = Option.none<Promise<BuildContext>>()\n let configWatcher = Option.none<FSWatcher>()\n let rereading = Option.none<ReturnType<typeof setTimeout>>()\n // Swaps run one at a time, in the order their changes arrived.\n let swaps: Promise<void> = Promise.resolve()\n let stopping = Option.none<Promise<void>>()\n const dispose = async (watcher: Promise<BuildContext>) => {\n // A context that never opened has nothing to dispose; its failure was the watch's to report.\n const opened = await watcher.then(Option.some, () => Option.none<BuildContext>())\n if (Option.isSome(opened)) await opened.value.dispose()\n }\n // Each step runs however the one before it ended: a step skipped leaves\n // workerd running, or the bundle's directory behind.\n const stopOnce = async () => {\n clearInterval(draining)\n closeMeter()\n Option.map(rereading, clearTimeout)\n Option.map(configWatcher, watcher => watcher.close())\n try {\n const watcher = watching\n watching = Option.none()\n // Waits for a rebuild in flight, whose step sees `stopping`.\n if (Option.isSome(watcher)) await dispose(watcher.value)\n await swaps\n } finally {\n try {\n await harness.close()\n } finally {\n // What the Worker wrote since the last drain, up to its end, is printed and kept.\n drain()\n await rm(directory, { recursive: true, force: true })\n }\n }\n }\n const stop = () =>\n Option.getOrElse(stopping, () => {\n const once = stopOnce()\n stopping = Option.some(once)\n return once\n })\n\n try {\n await writeOutputs(first)\n const { url } = await collect(spawned, () => harness.listen())\n // A reload at the same origin, as a swap is, before any request of the caller's.\n if (typeof given === 'function') {\n vars = given(url.origin)\n await collect(spawned, () => harness.update(optionsFor(raw, outfile, vars)))\n }\n const worker = harness.getWorker()\n const metered = workerdMeter(url.origin, worker.fetch, spawned)\n closeMeter = metered.close\n await migrate(worker, config)\n\n const watch = async (listener: WatchListener) => {\n if (Option.isSome(stopping)) throw new Error('This stack has stopped.')\n if (Option.isSome(watching)) throw new Error('This stack is already watching.')\n // None once a swap failed after its trial and took the runtime with it.\n let running = Option.some<Running>({ raw, config, files: first })\n\n /**\n * Starts `next` on a workerd of its own, then swaps it in. A Worker\n * that does not start is refused there, and the stack's harness, which\n * a failed update tears down with its storage, never sees it.\n */\n const swap = async (next: Running) => {\n try {\n await writeOutputs(\n next.files.map(file => ({\n path: join(trialDirectory, relative(directory, file.path)),\n contents: file.contents,\n })),\n )\n const trial = createTestHarness(\n optionsFor(next.raw, join(trialDirectory, basename(outfile)), vars),\n )\n try {\n await collect(trials, () => trial.listen())\n await migrate(trial.getWorker(), next.config)\n } finally {\n await trial.close()\n }\n } catch (error) {\n listener.onRefused(errorText(error))\n return\n }\n try {\n await writeOutputs(next.files)\n await collect(spawned, () => harness.update(optionsFor(next.raw, outfile, vars)))\n } catch (error) {\n running = Option.none()\n listener.onStopped(errorText(error))\n return\n }\n running = Option.some(next)\n try {\n await migrate(harness.getWorker(), next.config)\n } catch (error) {\n listener.onRefused(\n `The Worker was swapped in, but a migration failed: ${errorText(error)}`,\n )\n return\n }\n listener.onSwap()\n }\n /** Queues a swap of what `change` makes of the running stack, which may be none. */\n const enqueue = (change: (now: Running) => Promise<Option.Option<Running>>) => {\n const step = swaps.then(async () => {\n // A step that runs once `stop` began swaps nothing: `stop` waits for\n // it before closing the harness, so it would swap into a closing stack.\n if (Option.isNone(running) || Option.isSome(stopping)) return\n const next = await change(running.value)\n if (Option.isSome(next)) await swap(next.value)\n })\n // A listener that throws fails its own step, not the ones after it.\n swaps = step.catch(() => undefined)\n return step\n }\n\n const watcher = context({\n ...bundle,\n plugins: [\n ...bundle.plugins,\n {\n name: 'foldkit-swap',\n setup: build =>\n build.onEnd(result =>\n enqueue(async now => {\n if (result.errors.length > 0) {\n listener.onRefused(result.errors.map(error => error.text).join('\\n'))\n return Option.none()\n }\n const files = result.outputFiles ?? []\n // An editor saving in place empties the file before writing it, and a\n // rebuild can read it then; the write's own rebuild swaps.\n if (files.some(file => file.path === outfile && file.contents.length === 0)) {\n listener.onRefused(\n `${options.entry} bundles to no code, so no Worker could start.`,\n )\n return Option.none()\n }\n return identityOf(files) === identityOf(now.files)\n ? Option.none()\n : Option.some({ ...now, files })\n }),\n ),\n },\n ],\n })\n watching = Option.some(watcher)\n try {\n await (await watcher).watch()\n } catch (error) {\n // Not watching after all: `stop` must not wait on this context, nor a second `watch` be refused.\n if (Option.contains(watching, watcher)) {\n watching = Option.none()\n await dispose(watcher)\n }\n throw error\n }\n // A `stop` that began while the context opened would close no watcher made now.\n if (Option.isSome(stopping)) return\n\n const reread = () =>\n enqueue(async now => {\n const read = await readConfig(options.wrangler).then(Option.some, (error: unknown) => {\n listener.onRefused(errorText(error))\n return Option.none<Awaited<ReturnType<typeof readConfig>>>()\n })\n // A save that changed nothing the configuration says.\n return read.pipe(\n Option.filter(({ raw }) => JSON.stringify(raw) !== JSON.stringify(now.raw)),\n Option.map(({ raw, config }) => ({ ...now, raw, config })),\n )\n })\n // The directory, not the file: an editor that renames a temporary over the\n // file replaces what a file watcher watches.\n const name = basename(options.wrangler)\n configWatcher = Option.some(\n watchFile(dirname(options.wrangler), (_, changed) => {\n if (changed !== name) return\n // One reread for the burst of events a single save makes.\n Option.map(rereading, clearTimeout)\n rereading = Option.some(setTimeout(() => void reread(), 50))\n }).on('error', error =>\n listener.onRefused(`The configuration is no longer watched: ${errorText(error)}`),\n ),\n )\n }\n\n const env = () => harness.getWorker<Env>().getEnv()\n const logs = () => {\n drain()\n return kept.splice(0)\n }\n return {\n origin: url.origin,\n env,\n dispatch: worker.fetch,\n logs,\n cpu: metered.meter,\n watch,\n stop,\n }\n } catch (error) {\n // The start's failure is the one to report; a failure cleaning up after it would hide it.\n await stop().catch(() => undefined)\n throw error\n }\n}\n\n/**\n * The local Workers stack. `Stack.start` runs the Worker for tests and\n * development; `Stack.writeBundle` writes what `wrangler deploy` uploads,\n * bundled the same way.\n */\nexport const Stack = { start, writeBundle } as const\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAM,UAAU;AAEhB,MAAM,iBAAiB,KAAK,SAAS,kBAAkB,OAAO,WAAW;AACzE,MAAM,gBAAgB,KAAK,SAAS,iBAAiB,OAAO,UAA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CACR;AACF;;;;;;AAOA,MAAa,QAAQ;CAAE;CAAO;AAAY"}
1
+ {"version":3,"file":"workers.mjs","names":["watch","watchFile"],"sources":["../../src/testing/workers.ts"],"sourcesContent":["/**\n * `foldkit-plus/testing/workers`: a Worker on a local workerd, configured by\n * its own Wrangler configuration.\n *\n * Wrangler's test harness reads the configuration, so bindings, the\n * compatibility date and flags, `.dev.vars` and D1 migrations mean here what\n * they mean to `wrangler deploy`. This module owns only what Wrangler cannot\n * know: the bundle. esbuild builds the entry with the workspace's source\n * condition into a directory of the stack's own, and the harness runs the\n * configuration with `main` pointed there.\n *\n * `wrangler`, `esbuild` and `@foldkit/vite-plugin` are optional peers of\n * `foldkit-plus`, loaded on the first call; Miniflare is read from Wrangler's\n * own copy, so the date check asks the runtime Wrangler starts.\n */\nimport { Option, Schema } from 'effect'\nimport type {\n BuildContext,\n BuildOptions,\n Loader,\n OnLoadArgs,\n OnLoadResult,\n OutputFile,\n Plugin,\n} from 'esbuild'\nimport type { TestHarness, WorkerHandle } from 'wrangler'\nimport { ChildProcess, spawn } from 'node:child_process'\nimport { subscribe, unsubscribe } from 'node:diagnostics_channel'\nimport { readFileSync, watch as watchFile, type FSWatcher } from 'node:fs'\nimport { mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { createInterface } from 'node:readline'\nimport { createRequire } from 'node:module'\nimport { tmpdir } from 'node:os'\nimport { basename, dirname, extname, join, relative, resolve } from 'node:path'\nimport { peer } from './peer.js'\n\nconst SUBPATH = 'testing/workers'\n\nconst wrangler = () => peer(SUBPATH, 'wrangler', () => import('wrangler'))\nconst esbuild = () => peer(SUBPATH, 'esbuild', () => import('esbuild'))\nconst foldkitVite = () =>\n peer(SUBPATH, '@foldkit/vite-plugin', () => import('@foldkit/vite-plugin'))\n\nexport interface StackOptions {\n /** The Worker's Wrangler configuration (`wrangler.toml`, `.json` or `.jsonc`). */\n readonly wrangler: string\n /** The source esbuild bundles into what `main` names. */\n readonly entry: string\n /**\n * Local values for vars the deployed Worker is given elsewhere. As a\n * function, of the origin the stack answers at: the Worker has them from\n * its first request (`origin => ({ ORIGIN: origin })`).\n */\n readonly vars?: Vars | ((origin: string) => Vars)\n /** Local values for secrets, over any in `.dev.vars`. */\n readonly secrets?: Readonly<Record<string, string>>\n /**\n * esbuild plugins for the bundle, the deploy's and the stack's alike. A\n * module one loads is branded with view identities as one read from disk is.\n */\n readonly plugins?: ReadonlyArray<Plugin>\n /**\n * The Vite root of the page the Worker renders; by default the folder of\n * the Wrangler configuration. Each view is named by its module's path from\n * here, as `@foldkit/vite-plugin` names the page's.\n */\n readonly pageRoot?: string\n /**\n * Whether each line the Worker writes to its console is printed here, by\n * its level, as it arrives (`'print'`, the default). `logs()` keeps them either way.\n */\n readonly console?: 'print' | 'quiet'\n}\n\ntype Vars = Readonly<Record<string, string>>\n\n/** A line the Worker wrote to its console. An `Error` logged carries its stack in `message`. */\nexport interface WorkerLog {\n /** As workerd names it: `debug`, `info`, `log`, `warn` or `error`. */\n readonly level: string\n readonly message: string\n readonly timestamp: number\n}\n\n/**\n * What a watched stack reports after each change to the bundle's sources or\n * to the Wrangler configuration.\n */\nexport interface WatchListener {\n /** The new Worker answers at the same origin, over the same storage. */\n readonly onSwap: () => void\n /**\n * The change was not swapped in, and the Worker running keeps answering\n * over the same storage. It did not build, built no code (as an entry saved\n * in place reads for a moment), did not start when tried on a workerd of\n * its own, or is a configuration the stack refuses. Or it was swapped in,\n * and a D1 migration then failed on the running database; the message says so.\n */\n readonly onRefused: (message: string) => void\n /**\n * A Worker that started when tried did not start in the stack. Wrangler's\n * harness tears its runtime down with it, storage included, so the stack\n * has stopped answering and watches no more: call `stop`, and start again.\n */\n readonly onStopped: (message: string) => void\n}\n\nexport interface Stack<Env> {\n /** Where the Worker answers over real HTTP. */\n readonly origin: string\n /**\n * The Worker's bindings, as the Worker sees them. A swap retires the ones\n * read before it (Miniflare's \"poisoned stub\"), so read them after.\n */\n readonly env: () => Promise<Env>\n /** A request straight to the Worker; an upgrade answers with its socket. */\n readonly dispatch: WorkerHandle['fetch']\n /**\n * Takes what the Worker wrote to its console since the last call, oldest\n * first. The lines come from workerd beside the response, not on it, so a\n * line written for a request may arrive after it: poll.\n */\n readonly logs: () => ReadonlyArray<WorkerLog>\n /**\n * Requests sent straight to the Worker, metered for `Cpu.budget` by how\n * long workerd's main thread runs, read from the operating system since\n * workerd reports no CPU (Linux and Windows). That counts the Worker's code\n * and what workerd does on the thread around it, D1's SQLite included,\n * which a deployed Worker's CPU time leaves out.\n */\n readonly cpu: CpuMeter\n /**\n * Rebuilds on every change to a file the bundle read, and rereads the\n * Wrangler configuration when it changes. Each change is first started on\n * a workerd of its own, then swapped in at the same origin, and the D1\n * migrations not yet applied are applied. D1, R2 and Durable Object storage stay.\n */\n readonly watch: (listener: WatchListener) => Promise<void>\n /**\n * Stops watching, stops workerd and removes the bundle's directory, each\n * even when one before it failed. A change not yet being tried swaps\n * nothing and reports nothing; one being tried finishes first. A second\n * call returns the first one's promise.\n */\n readonly stop: () => Promise<void>\n}\n\n/** What a meter answers: a `Response`, or Miniflare's own. */\nexport type CpuAnswer = Pick<Response, 'status' | 'arrayBuffer'>\n\n/** Answers requests, and reads how much CPU time the code answering them has spent. */\nexport interface CpuMeter {\n /** What a route given as a path is resolved against. */\n readonly origin: string\n readonly fetch: (request: Request) => Promise<CpuAnswer>\n /** Milliseconds of CPU time spent so far, from a fixed point of the meter's own. */\n readonly spent: () => Promise<number>\n}\n\n/**\n * A route `Cpu.budget` asks: a path or URL to `GET`, or a function making\n * a new request for each run, since a request's body is read once.\n */\nexport type CpuRoute = string | (() => Request)\n\n/** What one route cost, in milliseconds of CPU time. */\nexport interface CpuReading {\n readonly route: string\n /** The last response's status. */\n readonly status: number\n /** The route's first request in this call: in a fresh stack, a cold isolate's. */\n readonly cold: number\n /**\n * The most a request after the first spent, in milliseconds. A deployed\n * Worker's limit applies to each request, not to their mean.\n */\n readonly warm: number\n}\n\nexport interface CpuBudget {\n /** The routes, by the name a failure reports them with. */\n readonly routes: Readonly<Record<string, CpuRoute>>\n /**\n * Milliseconds each request after the first may spend. A meter's own\n * resolution bounds how small this can be: Windows books a thread's CPU\n * time in 15.6 ms ticks, so a budget near that reads one request's cost\n * as a tick whether it spent it or not.\n */\n readonly warm: number\n /** Milliseconds the first request may spend; unchecked when not given. */\n readonly cold?: number\n /** Requests after the first, each answered in full before the next; default 5. */\n readonly runs?: number\n}\n\n/** The processes spawned while a stack's harness starts or reloads; workerd among them. */\ninterface Spawned {\n readonly processes: Array<ChildProcess>\n /** Another stack spawned at the same time, so whose process is whose is unknown. */\n shared: boolean\n}\n\nconst collecting = new Set<Spawned>()\n\n// Named once spawned: Node publishes a process before it starts it.\nconst isWorkerd = (child: ChildProcess) =>\n typeof child.spawnfile === 'string' && /^workerd(\\.exe)?$/.test(basename(child.spawnfile))\n\n// Node publishes every `spawn` here, workerd's by Miniflare included; the\n// harness offers no other way to find the process.\nconst onSpawn = (message: unknown) => {\n if (typeof message !== 'object' || message === null || !('process' in message)) return\n const child = message.process\n if (!(child instanceof ChildProcess)) return\n for (const spawned of collecting) spawned.processes.push(child)\n}\n\n/** Runs `step`, adding the processes it spawns to `into`. */\nconst collect = async <A>(into: Spawned, step: () => Promise<A>): Promise<A> => {\n if (collecting.size === 0) subscribe('child_process', onSpawn)\n for (const other of collecting) other.shared = into.shared = true\n collecting.add(into)\n try {\n return await step()\n } finally {\n collecting.delete(into)\n if (collecting.size === 0) unsubscribe('child_process', onSpawn)\n }\n}\n\nconst isRunning = (child: ChildProcess) => child.exitCode === null && child.signalCode === null\n\n/** Milliseconds a Linux process's main thread has run, by the scheduler's nanoseconds. */\nconst linuxTime = async (pid: number): Promise<number> =>\n Number((await readFile(`/proc/${pid}/task/${pid}/schedstat`, 'utf8')).split(' ')[0]) / 1e6\n\n/**\n * Reads how long processes' main threads have run, where workerd runs\n * JavaScript. V8's helper threads, which collect garbage and compile beside\n * it, are left out: on a server-rendered page they added half as much again.\n */\ninterface CpuReader {\n readonly read: (pids: ReadonlyArray<number>) => Promise<number>\n readonly close: () => void\n}\n\nconst linuxReader = (): CpuReader => ({\n read: async pids => (await Promise.all(pids.map(linuxTime))).reduce((a, b) => a + b, 0),\n close: () => {},\n})\n\n/**\n * Windows has no `/proc`, and Node no call for another process's times, so\n * one PowerShell kept open answers each read: started per read, it takes\n * longer than the requests it measures. The main thread is the one that\n * started first. Windows adds to a thread's time a scheduler tick (15.6 ms)\n * at a time.\n */\nconst windowsReader = (): CpuReader => {\n const shell = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', '-'], {\n stdio: ['pipe', 'pipe', 'ignore'],\n windowsHide: true,\n })\n const waiting: Array<(line: Option.Option<string>) => void> = []\n createInterface({ input: shell.stdout }).on('line', line => waiting.shift()?.(Option.some(line)))\n // A shell that could not start, or ended, answers no read waiting on it.\n const ended = () => waiting.splice(0).forEach(answer => answer(Option.none()))\n shell.on('error', ended).on('exit', ended)\n return {\n read: pids =>\n new Promise((resolve, reject) => {\n waiting.push(line => {\n const ticks = Number(Option.getOrElse(line, () => ''))\n if (Option.isSome(line) && Number.isFinite(ticks)) resolve(ticks / 1e4)\n else\n reject(\n new Error(\n `workerd's CPU time could not be read: ${Option.getOrElse(line, () => 'PowerShell ended')}`,\n ),\n )\n })\n shell.stdin.write(\n `try { (@(${pids.join(',')}) | % { ([Diagnostics.Process]::GetProcessById($_).Threads | Sort-Object StartTime | Select-Object -First 1).TotalProcessorTime.Ticks } | Measure-Object -Sum).Sum } catch { \"$_\" }\\n`,\n )\n }),\n close: () => shell.kill(),\n }\n}\n\nconst readerFor = (): CpuReader => {\n if (process.platform === 'linux') return linuxReader()\n if (process.platform === 'win32') return windowsReader()\n throw new Error(\n `The stack reads workerd's CPU time on Linux and Windows, not ${process.platform}.`,\n )\n}\n\n/** The CPU meter over a stack's workerd processes, its reader made on the first read. */\nconst workerdMeter = (origin: string, dispatch: WorkerHandle['fetch'], spawned: Spawned) => {\n let reader = Option.none<CpuReader>()\n const meter: CpuMeter = {\n origin,\n // Straight to the Worker: over `origin` a second workerd, which proxies\n // what the harness serves, would spend time of its own on every request.\n fetch: async request =>\n dispatch(request.url, {\n method: request.method,\n headers: [...request.headers],\n ...(request.body === null ? {} : { body: await request.arrayBuffer() }),\n }),\n spent: async () => {\n if (spawned.shared)\n throw new Error(\n 'Another stack started in this process while this one did, so whose workerd is ' +\n \"whose is unknown: start stacks one at a time to read a stack's CPU.\",\n )\n const current = Option.getOrElse(reader, readerFor)\n reader = Option.some(current)\n return current.read(\n spawned.processes\n .filter(child => isWorkerd(child) && isRunning(child))\n .flatMap(child => (child.pid === undefined ? [] : [child.pid])),\n )\n },\n }\n return { meter, close: () => Option.map(reader, open => open.close()) }\n}\n\n/**\n * Asks each route once, then `runs` times more, one request at a time, each\n * response read in full, and reads what each cost. Every warm request is\n * checked, since a deployed Worker's limit applies to each rather than to\n * their mean. Throws listing every reading when a route spends more than\n * the budget, or answers a 5xx, whose cost says nothing of the route's.\n */\nconst budget = async (\n meter: CpuMeter,\n { routes, warm, cold, runs = 5 }: CpuBudget,\n): Promise<ReadonlyArray<CpuReading>> => {\n if (!Number.isInteger(runs) || runs < 1)\n throw new Error(`Cpu.budget: runs must be a whole number from 1, not ${runs}.`)\n const requestOf = (route: CpuRoute) =>\n typeof route === 'string' ? new Request(new URL(route, meter.origin)) : route()\n const readings: Array<CpuReading> = []\n for (const [name, route] of Object.entries(routes)) {\n let status = 0\n const ask = async () => {\n const response = await meter.fetch(requestOf(route))\n await response.arrayBuffer()\n status = response.status\n if (status >= 500) throw new Error(`Cpu.budget: ${name} answered ${status}.`)\n }\n const start = await meter.spent()\n await ask()\n const first = await meter.spent()\n let warmest = 0\n let previous = first\n for (let run = 0; run < runs; run++) {\n await ask()\n const now = await meter.spent()\n warmest = Math.max(warmest, now - previous)\n previous = now\n }\n readings.push({ route: name, status, cold: first - start, warm: warmest })\n }\n const over = readings.filter(\n reading => reading.warm > warm || (cold !== undefined && reading.cold > cold),\n )\n if (over.length > 0)\n throw new Error(\n `Over the CPU budget (warm ${warm} ms${cold === undefined ? '' : `, cold ${cold} ms`}): ` +\n `${over.map(reading => reading.route).join(', ')}\\n` +\n readings\n .map(\n reading =>\n ` ${reading.route}: cold ${reading.cold.toFixed(2)} ms, ` +\n `warm ${reading.warm.toFixed(2)} ms (status ${reading.status})`,\n )\n .join('\\n'),\n )\n return readings\n}\n\nconst pause = new Int32Array(new SharedArrayBuffer(4))\n\n/**\n * Milliseconds this thread has run. Linux books a running thread's time at\n * each scheduler tick (4 ms at 250 Hz), and `threadCpuUsage` reads that\n * book; a millisecond's sleep has the scheduler book the rest, and its own\n * count is in nanoseconds. Read synchronously, so on this thread rather\n * than the pool's.\n */\nconst threadTime = (): number => {\n if (process.platform === 'linux') {\n Atomics.wait(pause, 0, 0, 1)\n return Number(readFileSync('/proc/thread-self/schedstat', 'utf8').split(' ')[0]) / 1e6\n }\n const { user, system } = process.threadCpuUsage()\n return (user + system) / 1000\n}\n\n/**\n * A meter over `answer` run in this process, by this thread's CPU time: for\n * a Worker's handler Node can run (no D1 or other binding of workerd's),\n * whose work happens on the thread that awaits it.\n */\nconst inThread = (\n answer: (request: Request) => Promise<CpuAnswer>,\n origin = 'http://localhost',\n): CpuMeter => ({ origin, fetch: answer, spent: async () => threadTime() })\n\n/**\n * What a request costs in CPU time, which Miniflare neither limits nor\n * reports, while a deployed Worker fails past its plan's limit (error 1102).\n * `Cpu.budget` reads routes through a meter: a stack's `cpu`, or `Cpu.inThread`.\n */\nexport const Cpu = { budget, inThread } as const\n\n/**\n * The part of the configuration the stack reads itself. Wrangler validates\n * the whole of it when the harness loads it.\n */\nconst Config = Schema.Struct({\n main: Schema.String,\n compatibility_date: Schema.String,\n // The stack bundles; Wrangler bundling `main` again would deploy other code.\n no_bundle: Schema.Literal(true),\n d1_databases: Schema.optional(Schema.Array(Schema.Struct({ binding: Schema.String }))),\n})\n\n/**\n * The newest date the workerd Wrangler starts supports, from Wrangler's own\n * Miniflare: an application's own `miniflare` may be another release. Call it\n * after `wrangler()`, which says so when Wrangler is missing.\n */\nconst supportedDate = (): string => {\n const fromWrangler = createRequire(createRequire(import.meta.url).resolve('wrangler'))\n return Schema.decodeUnknownSync(Schema.Struct({ supportedCompatibilityDate: Schema.String }))(\n fromWrangler('miniflare'),\n ).supportedCompatibilityDate\n}\n\nconst readConfig = async (path: string) => {\n const { experimental_readRawConfig } = await wrangler()\n const { rawConfig: raw } = experimental_readRawConfig({ config: path })\n if ('env' in raw)\n throw new Error(`${path}: the local stack runs the top-level Worker; [env.*] is not read.`)\n const config = Schema.decodeUnknownSync(Config)(raw)\n // Miniflare would run a date it does not know at its own latest, with a\n // warning nobody reads, and the tests would pass on a runtime the deploy does not get.\n const supported = supportedDate()\n if (config.compatibility_date > supported)\n throw new Error(\n `${path} asks for compatibility_date ${config.compatibility_date}, but the installed ` +\n `workerd supports up to ${supported}. Move wrangler to a release that knows it.`,\n )\n return { raw, config }\n}\n\n// The modules Vite's view-identity transform reads, and the loader each is read with.\nconst scriptLoaders: Readonly<Record<string, Loader>> = {\n '.ts': 'ts',\n '.mts': 'ts',\n '.tsx': 'tsx',\n '.js': 'js',\n '.mjs': 'js',\n '.jsx': 'jsx',\n}\nconst SCRIPT = /\\.(?:ts|tsx|js|jsx|mts|mjs)$/\nconst scripts = new Set(Object.values(scriptLoaders))\n// Vite skips installed packages: Foldkit's own, whose brand would stamp every vnode as it is made.\nconst isPackaged = (path: string) => /[\\\\/]node_modules[\\\\/]/.test(path)\n\n/**\n * The plugins, with the Worker's views branded as `@foldkit/vite-plugin`\n * brands the page's build: each function's result named by its module's path\n * from `root`. Foldkit adopts a served element only where that name is the\n * one the browser's view gives it; unbranded, the Worker's page was rebuilt on\n * every hydration, silently in production (#412).\n *\n * Vite brands what any load returns, but esbuild takes the first `onLoad`\n * that answers, so each plugin's is wrapped and a module it loads (with\n * `pnpm mutate`'s edits, say) is branded too. `foldkit/brand` resolves from\n * `root`, as the page's does; a root that resolves none has no Foldkit page\n * to match, and the Worker is bundled as written.\n */\nconst viewIdentity = (root: string, plugins: ReadonlyArray<Plugin>): Array<Plugin> => {\n // Found at each build's start, so a watched stack sees Foldkit installed.\n let brand = Option.none<string>()\n const resolving = Symbol('foldkit/brand')\n const brands = ({ path, namespace }: OnLoadArgs) =>\n Option.isSome(brand) && namespace === 'file' && SCRIPT.test(path) && !isPackaged(path)\n /** `contents` branded, or none where nothing in them returns. */\n const branded = async (\n contents: string | Uint8Array,\n loader: Loader,\n path: string,\n ): Promise<Option.Option<string>> => {\n const { transform } = await esbuild()\n const { transformViewIdentity } = await foldkitVite()\n // The brand reads JavaScript, as Vite hands it over after its own TypeScript pass.\n const { code } = await transform(contents, { loader, sourcefile: path })\n return Option.fromNullOr(transformViewIdentity(code, path, root)).pipe(\n Option.map(result => result.code),\n )\n }\n const brandedResult = async (result: OnLoadResult, args: OnLoadArgs): Promise<OnLoadResult> => {\n const loader = result.loader ?? scriptLoaders[extname(args.path)]\n const { contents } = result\n if (!brands(args) || contents === undefined || loader === undefined || !scripts.has(loader))\n return result\n return Option.match(await branded(contents, loader, args.path), {\n onNone: () => result,\n onSome: contents => ({ ...result, contents, loader: 'js' }),\n })\n }\n const wrapped = (plugin: Plugin): Plugin => ({\n ...plugin,\n setup: build =>\n plugin.setup({\n ...build,\n onLoad: (options, load) =>\n build.onLoad(options, async args => {\n const result = await load(args)\n return result === null || result === undefined ? result : brandedResult(result, args)\n }),\n }),\n })\n return [\n {\n name: 'foldkit-view-identity',\n setup: build => {\n build.onStart(async () => {\n const found = await build.resolve('foldkit/brand', {\n kind: 'import-statement',\n resolveDir: root,\n pluginData: resolving,\n })\n brand = found.errors.length === 0 ? Option.some(found.path) : Option.none()\n })\n build.onResolve({ filter: /^foldkit\\/brand$/ }, args =>\n args.pluginData === resolving\n ? undefined\n : Option.match(brand, { onNone: () => undefined, onSome: path => ({ path }) }),\n )\n },\n },\n ...plugins.map(wrapped),\n {\n // Last: a module no plugin loaded, read from disk.\n name: 'foldkit-view-identity-load',\n setup: build =>\n build.onLoad({ filter: SCRIPT }, async args => {\n const loader = scriptLoaders[extname(args.path)]\n if (!brands(args) || loader === undefined) return undefined\n const code = await branded(await readFile(args.path), loader, args.path)\n return Option.match(code, {\n onNone: () => undefined,\n onSome: contents => ({ contents, loader: 'js' as const }),\n })\n }),\n },\n ]\n}\n\n/**\n * How the entry is bundled, for the stack and for `wrangler deploy`: the\n * script at `outfile`, and beside it any `.wasm` it imports, which `no_bundle`\n * Wrangler loads as a compiled module. `node:*` stays external for\n * `nodejs_compat`.\n */\nconst bundleOptions = (options: StackOptions, outfile: string) =>\n ({\n entryPoints: [options.entry],\n bundle: true,\n format: 'esm',\n platform: 'browser',\n conditions: ['foldkit-plus:source'],\n external: ['cloudflare:workers', 'node:*'],\n loader: { '.wasm': 'copy' },\n plugins: viewIdentity(\n resolve(options.pageRoot ?? dirname(options.wrangler)),\n options.plugins ?? [],\n ),\n outdir: dirname(outfile),\n entryNames: basename(outfile, '.js'),\n write: false,\n logLevel: 'silent',\n }) satisfies BuildOptions\n\ntype OutputFiles = ReadonlyArray<OutputFile>\n\nconst writeOutputs = async (\n files: ReadonlyArray<{ readonly path: string; readonly contents: Uint8Array }>,\n) => {\n for (const file of files) {\n await mkdir(dirname(file.path), { recursive: true })\n await writeFile(file.path, file.contents)\n }\n}\n\nconst identityOf = (files: OutputFiles) => files.map(file => `${file.path}:${file.hash}`).join()\n\n/** Node's console method for each level workerd writes; any other prints as a log. */\nconst printers = new Map<string, (line: string) => void>([\n ['debug', line => console.debug(line)],\n ['info', line => console.info(line)],\n ['warn', line => console.warn(line)],\n ['error', line => console.error(line)],\n])\n\nconst print = (log: WorkerLog) =>\n (printers.get(log.level) ?? (line => console.log(line)))(`[worker] ${log.message}`)\n\nconst errorText = (error: unknown) => (error instanceof Error ? error.message : String(error))\n\n/** Writes the bundle where `main` says, for `wrangler deploy`. */\nconst writeBundle = async (options: Omit<StackOptions, 'vars' | 'secrets'>): Promise<void> => {\n const { config } = await readConfig(options.wrangler)\n const outfile = resolve(dirname(options.wrangler), config.main)\n const { build } = await esbuild()\n await writeOutputs((await build(bundleOptions(options, outfile))).outputFiles)\n}\n\ntype Raw = Awaited<ReturnType<typeof readConfig>>['raw']\n\n/** What the stack runs: a configuration and a bundle, swapped in together. */\ninterface Running {\n readonly raw: Raw\n readonly config: typeof Config.Type\n readonly files: OutputFiles\n}\n\nconst migrate = async (worker: WorkerHandle, config: typeof Config.Type) => {\n for (const database of config.d1_databases ?? []) await worker.applyD1Migrations(database.binding)\n}\n\n/**\n * Starts the Worker with a fresh, migrated D1 for each `[[d1_databases]]`,\n * and empty R2 and Durable Object storage. Each call is a stack of its own,\n * so test files running side by side share nothing.\n */\nconst start = async <Env>(options: StackOptions): Promise<Stack<Env>> => {\n const { raw, config } = await readConfig(options.wrangler)\n const { build, context } = await esbuild()\n const { createTestHarness } = await wrangler()\n const directory = join(tmpdir(), `foldkit-workers-${crypto.randomUUID()}`)\n const outfile = join(directory, basename(config.main))\n // Where a change is started on a workerd of its own before the swap.\n const trialDirectory = join(directory, 'trial')\n const bundle = bundleOptions(options, outfile)\n // In memory: a source that does not build fails here, before anything exists to clean up.\n const first = (await build(bundle)).outputFiles\n\n const optionsFor = (raw: Raw, main: string, vars: Vars | undefined) => ({\n root: dirname(options.wrangler),\n workers: [{ config: { ...raw, main }, vars, secrets: options.secrets }],\n })\n const given = options.vars\n // Given here, or once the stack knows its origin.\n let vars = typeof given === 'function' ? undefined : given\n const harness: TestHarness = createTestHarness(optionsFor(raw, outfile, vars))\n const spawned: Spawned = { processes: [], shared: false }\n // Where a trial's workerd goes: collected only so that a stack starting beside it knows.\n const trials: Spawned = { processes: [], shared: false }\n let closeMeter = () => {}\n // The harness keeps workerd's console and offers no handler, so it is drained:\n // read and cleared in one synchronous step, nothing is read twice or missed.\n const kept: Array<WorkerLog> = []\n const drain = () => {\n const fresh = harness.getLogs()\n harness.clearLogs()\n if (options.console !== 'quiet') fresh.forEach(print)\n kept.push(...fresh)\n }\n const draining = setInterval(drain, 100)\n draining.unref()\n let watching = Option.none<Promise<BuildContext>>()\n let configWatcher = Option.none<FSWatcher>()\n let rereading = Option.none<ReturnType<typeof setTimeout>>()\n // Swaps run one at a time, in the order their changes arrived.\n let swaps: Promise<void> = Promise.resolve()\n let stopping = Option.none<Promise<void>>()\n const dispose = async (watcher: Promise<BuildContext>) => {\n // A context that never opened has nothing to dispose; its failure was the watch's to report.\n const opened = await watcher.then(Option.some, () => Option.none<BuildContext>())\n if (Option.isSome(opened)) await opened.value.dispose()\n }\n // Each step runs however the one before it ended: a step skipped leaves\n // workerd running, or the bundle's directory behind.\n const stopOnce = async () => {\n clearInterval(draining)\n closeMeter()\n Option.map(rereading, clearTimeout)\n Option.map(configWatcher, watcher => watcher.close())\n try {\n const watcher = watching\n watching = Option.none()\n // Waits for a rebuild in flight, whose step sees `stopping`.\n if (Option.isSome(watcher)) await dispose(watcher.value)\n await swaps\n } finally {\n try {\n await harness.close()\n } finally {\n // What the Worker wrote since the last drain, up to its end, is printed and kept.\n drain()\n await rm(directory, { recursive: true, force: true })\n }\n }\n }\n const stop = () =>\n Option.getOrElse(stopping, () => {\n const once = stopOnce()\n stopping = Option.some(once)\n return once\n })\n\n try {\n await writeOutputs(first)\n const { url } = await collect(spawned, () => harness.listen())\n // A reload at the same origin, as a swap is, before any request of the caller's.\n if (typeof given === 'function') {\n vars = given(url.origin)\n await collect(spawned, () => harness.update(optionsFor(raw, outfile, vars)))\n }\n const worker = harness.getWorker()\n const metered = workerdMeter(url.origin, worker.fetch, spawned)\n closeMeter = metered.close\n await migrate(worker, config)\n\n const watch = async (listener: WatchListener) => {\n if (Option.isSome(stopping)) throw new Error('This stack has stopped.')\n if (Option.isSome(watching)) throw new Error('This stack is already watching.')\n // None once a swap failed after its trial and took the runtime with it.\n let running = Option.some<Running>({ raw, config, files: first })\n\n /**\n * Starts `next` on a workerd of its own, then swaps it in. A Worker\n * that does not start is refused there, and the stack's harness, which\n * a failed update tears down with its storage, never sees it.\n */\n const swap = async (next: Running) => {\n try {\n await writeOutputs(\n next.files.map(file => ({\n path: join(trialDirectory, relative(directory, file.path)),\n contents: file.contents,\n })),\n )\n const trial = createTestHarness(\n optionsFor(next.raw, join(trialDirectory, basename(outfile)), vars),\n )\n try {\n await collect(trials, () => trial.listen())\n await migrate(trial.getWorker(), next.config)\n } finally {\n await trial.close()\n }\n } catch (error) {\n listener.onRefused(errorText(error))\n return\n }\n try {\n await writeOutputs(next.files)\n await collect(spawned, () => harness.update(optionsFor(next.raw, outfile, vars)))\n } catch (error) {\n running = Option.none()\n listener.onStopped(errorText(error))\n return\n }\n running = Option.some(next)\n try {\n await migrate(harness.getWorker(), next.config)\n } catch (error) {\n listener.onRefused(\n `The Worker was swapped in, but a migration failed: ${errorText(error)}`,\n )\n return\n }\n listener.onSwap()\n }\n /** Queues a swap of what `change` makes of the running stack, which may be none. */\n const enqueue = (change: (now: Running) => Promise<Option.Option<Running>>) => {\n const step = swaps.then(async () => {\n // A step that runs once `stop` began swaps nothing: `stop` waits for\n // it before closing the harness, so it would swap into a closing stack.\n if (Option.isNone(running) || Option.isSome(stopping)) return\n const next = await change(running.value)\n if (Option.isSome(next)) await swap(next.value)\n })\n // A listener that throws fails its own step, not the ones after it.\n swaps = step.catch(() => undefined)\n return step\n }\n\n const watcher = context({\n ...bundle,\n plugins: [\n ...bundle.plugins,\n {\n name: 'foldkit-swap',\n setup: build =>\n build.onEnd(result =>\n enqueue(async now => {\n if (result.errors.length > 0) {\n listener.onRefused(result.errors.map(error => error.text).join('\\n'))\n return Option.none()\n }\n const files = result.outputFiles ?? []\n // An editor saving in place empties the file before writing it, and a\n // rebuild can read it then; the write's own rebuild swaps.\n if (files.some(file => file.path === outfile && file.contents.length === 0)) {\n listener.onRefused(\n `${options.entry} bundles to no code, so no Worker could start.`,\n )\n return Option.none()\n }\n return identityOf(files) === identityOf(now.files)\n ? Option.none()\n : Option.some({ ...now, files })\n }),\n ),\n },\n ],\n })\n watching = Option.some(watcher)\n try {\n await (await watcher).watch()\n } catch (error) {\n // Not watching after all: `stop` must not wait on this context, nor a second `watch` be refused.\n if (Option.contains(watching, watcher)) {\n watching = Option.none()\n await dispose(watcher)\n }\n throw error\n }\n // A `stop` that began while the context opened would close no watcher made now.\n if (Option.isSome(stopping)) return\n\n const reread = () =>\n enqueue(async now => {\n const read = await readConfig(options.wrangler).then(Option.some, (error: unknown) => {\n listener.onRefused(errorText(error))\n return Option.none<Awaited<ReturnType<typeof readConfig>>>()\n })\n // A save that changed nothing the configuration says.\n return read.pipe(\n Option.filter(({ raw }) => JSON.stringify(raw) !== JSON.stringify(now.raw)),\n Option.map(({ raw, config }) => ({ ...now, raw, config })),\n )\n })\n // The directory, not the file: an editor that renames a temporary over the\n // file replaces what a file watcher watches.\n const name = basename(options.wrangler)\n configWatcher = Option.some(\n watchFile(dirname(options.wrangler), (_, changed) => {\n if (changed !== name) return\n // One reread for the burst of events a single save makes.\n Option.map(rereading, clearTimeout)\n rereading = Option.some(setTimeout(() => void reread(), 50))\n }).on('error', error =>\n listener.onRefused(`The configuration is no longer watched: ${errorText(error)}`),\n ),\n )\n }\n\n const env = () => harness.getWorker<Env>().getEnv()\n const logs = () => {\n drain()\n return kept.splice(0)\n }\n return {\n origin: url.origin,\n env,\n dispatch: worker.fetch,\n logs,\n cpu: metered.meter,\n watch,\n stop,\n }\n } catch (error) {\n // The start's failure is the one to report; a failure cleaning up after it would hide it.\n await stop().catch(() => undefined)\n throw error\n }\n}\n\n/**\n * The local Workers stack. `Stack.start` runs the Worker for tests and\n * development; `Stack.writeBundle` writes what `wrangler deploy` uploads,\n * bundled the same way.\n */\nexport const Stack = { start, writeBundle } as const\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAM,UAAU;AAEhB,MAAM,iBAAiB,KAAK,SAAS,kBAAkB,OAAO,WAAW;AACzE,MAAM,gBAAgB,KAAK,SAAS,iBAAiB,OAAO,UAAU;AACtE,MAAM,oBACJ,KAA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;EAEd,MAAM,KAAK,CAAC,CAAC,YAAY,KAAA,CAAS;EAClC,MAAM;CACR;AACF;;;;;;AAOA,MAAa,QAAQ;CAAE;CAAO;AAAY"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "foldkit-plus",
3
- "version": "0.19.0",
3
+ "version": "0.20.0",
4
4
  "description": "Every Foldkit Plus package in one install, `npx foldkit-plus setup`, which tells a coding agent how to start, and `npx foldkit-plus docs`, which answers from the installed docs.",
5
5
  "keywords": [
6
6
  "foldkit",
@@ -323,6 +323,11 @@
323
323
  "types": "./dist/mixins/foundations.d.mts",
324
324
  "import": "./dist/mixins/foundations.mjs"
325
325
  },
326
+ "./mixins/vite": {
327
+ "foldkit-plus:source": "./src/mixins/vite.ts",
328
+ "types": "./dist/mixins/vite.d.mts",
329
+ "import": "./dist/mixins/vite.mjs"
330
+ },
326
331
  "./mixins-builder": {
327
332
  "foldkit-plus:source": "./src/mixins-builder.ts",
328
333
  "types": "./dist/mixins-builder.d.mts",
@@ -625,43 +630,43 @@
625
630
  "LICENSE"
626
631
  ],
627
632
  "dependencies": {
628
- "foldkit-agent-a2a": "0.8.0",
629
- "foldkit-agent-webmcp": "0.9.0",
630
- "foldkit-agent-mcp": "0.9.0",
631
- "foldkit-builder": "0.5.0",
632
- "foldkit-bundle": "0.10.0",
633
- "foldkit-agent": "0.10.0",
634
- "foldkit-bundle-surface": "0.6.0",
635
- "foldkit-cms": "0.10.0",
636
- "foldkit-composition": "0.5.0",
637
- "foldkit-data-grid": "0.5.0",
638
- "foldkit-durable": "0.11.0",
639
- "foldkit-form": "0.10.0",
640
- "foldkit-entity": "0.15.0",
641
- "foldkit-guard": "0.8.0",
642
- "foldkit-media": "0.5.0",
643
- "foldkit-form-recipes": "0.3.0",
633
+ "foldkit-agent": "0.11.0",
634
+ "foldkit-agent-a2a": "0.9.0",
635
+ "foldkit-builder": "0.6.0",
636
+ "foldkit-agent-mcp": "0.10.0",
637
+ "foldkit-agent-webmcp": "0.10.0",
638
+ "foldkit-bundle-surface": "0.7.0",
639
+ "foldkit-bundle": "0.11.0",
640
+ "foldkit-cms": "0.11.0",
641
+ "foldkit-composition": "0.6.0",
642
+ "foldkit-crud": "0.14.0",
643
+ "foldkit-data-grid": "0.6.0",
644
+ "foldkit-durable": "0.12.0",
645
+ "foldkit-entity": "0.16.0",
646
+ "foldkit-form-recipes": "0.4.0",
647
+ "foldkit-guard": "0.9.0",
648
+ "foldkit-media": "0.6.0",
649
+ "foldkit-form": "0.11.0",
650
+ "foldkit-mirror": "0.9.0",
651
+ "foldkit-mixins-builder": "0.6.0",
652
+ "foldkit-mixins-data-grid": "0.5.0",
653
+ "foldkit-mixins-crud": "0.12.0",
654
+ "foldkit-mixins-form": "0.13.0",
644
655
  "foldkit-metadata": "0.1.0",
645
- "foldkit-mixins": "0.22.0",
646
- "foldkit-crud": "0.13.0",
647
- "foldkit-mirror": "0.8.0",
648
- "foldkit-mixins-builder": "0.5.0",
649
- "foldkit-mixins-crud": "0.11.0",
650
- "foldkit-mixins-form": "0.12.0",
651
- "foldkit-mixins-surface": "0.8.0",
652
- "foldkit-mixins-richtext": "0.7.0",
653
- "foldkit-mixins-data-grid": "0.4.0",
654
- "foldkit-richtext": "0.7.0",
655
- "foldkit-remote": "0.23.0",
656
- "foldkit-primitives": "0.17.0",
657
- "foldkit-remote-server": "0.20.0",
658
- "foldkit-richtext-code": "0.4.0",
659
- "foldkit-richtext-dom": "0.8.0",
660
- "foldkit-richtext-markdown": "0.5.0",
661
- "foldkit-site": "0.6.0",
662
- "foldkit-surface": "0.12.0",
663
- "foldkit-ssr": "0.10.0",
664
- "foldkit-sync": "0.14.0"
656
+ "foldkit-mixins": "0.23.0",
657
+ "foldkit-mixins-richtext": "0.8.0",
658
+ "foldkit-mixins-surface": "0.9.0",
659
+ "foldkit-primitives": "0.18.0",
660
+ "foldkit-remote": "0.24.0",
661
+ "foldkit-richtext": "0.8.0",
662
+ "foldkit-remote-server": "0.21.0",
663
+ "foldkit-richtext-code": "0.5.0",
664
+ "foldkit-richtext-dom": "0.9.0",
665
+ "foldkit-richtext-markdown": "0.6.0",
666
+ "foldkit-ssr": "0.11.0",
667
+ "foldkit-surface": "0.13.0",
668
+ "foldkit-sync": "0.15.0",
669
+ "foldkit-site": "0.7.0"
665
670
  },
666
671
  "peerDependencies": {
667
672
  "effect": "^4.1.0",
@@ -670,14 +675,14 @@
670
675
  "esbuild": "^0.28.0",
671
676
  "playwright": "^1.64.0",
672
677
  "wrangler": "^4.116.0",
673
- "foldkit-auth": "^0.3.0",
674
- "foldkit-agent-native": "^0.8.0",
675
- "foldkit-react": "^0.6.0",
676
- "foldkit-remote-drizzle": "^0.17.0",
678
+ "foldkit-auth": "^0.4.0",
679
+ "foldkit-cms-drizzle": "^0.9.0",
680
+ "foldkit-agent-native": "^0.9.0",
681
+ "foldkit-react": "^0.7.0",
682
+ "foldkit-mixins-ui": "^0.24.0",
683
+ "foldkit-remote-drizzle": "^0.18.0",
677
684
  "foldkit-react-codegen": "^0.3.0",
678
- "foldkit-mixins-ui": "^0.23.0",
679
- "foldkit-cms-drizzle": "^0.8.0",
680
- "foldkit-richtext-code-shiki": "^0.4.0"
685
+ "foldkit-richtext-code-shiki": "^0.5.0"
681
686
  },
682
687
  "peerDependenciesMeta": {
683
688
  "foldkit-agent-native": {
@@ -729,14 +734,14 @@
729
734
  "typescript": "7.0.2",
730
735
  "vite": "8.3.5",
731
736
  "wrangler": "4.116.0",
732
- "foldkit-auth": "0.3.0",
733
- "foldkit-agent-native": "0.8.0",
734
- "foldkit-cms-drizzle": "0.8.0",
735
- "foldkit-mixins-ui": "0.23.0",
736
- "foldkit-react": "0.6.0",
737
+ "foldkit-agent-native": "0.9.0",
738
+ "foldkit-auth": "0.4.0",
739
+ "foldkit-cms-drizzle": "0.9.0",
737
740
  "foldkit-react-codegen": "0.3.0",
738
- "foldkit-richtext-code-shiki": "0.4.0",
739
- "foldkit-remote-drizzle": "0.17.0"
741
+ "foldkit-react": "0.7.0",
742
+ "foldkit-mixins-ui": "0.24.0",
743
+ "foldkit-richtext-code-shiki": "0.5.0",
744
+ "foldkit-remote-drizzle": "0.18.0"
740
745
  },
741
746
  "setup": {
742
747
  "foldkit": "0.170.0",