foldkit-plus 0.17.0 → 0.18.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.
@@ -1 +1 @@
1
- {"version":3,"file":"setup.mjs","names":[],"sources":["../src/setup.ts"],"sourcesContent":["/**\n * What `npx foldkit-plus setup` prints: instructions a coding agent can follow\n * in order, for the project it is run in. Pure: the CLI reads the project and\n * this package's manifest and passes them in, so a test can give any project.\n */\nimport { Option } from 'effect'\n\nexport type Manager = 'pnpm' | 'npm' | 'yarn' | 'bun'\n\n/** What the project's `package.json` says about the libraries Foldkit Plus needs. */\nexport interface Project {\n readonly name: string\n /** Each named library's version range, from any dependency field. */\n readonly versions: Readonly<Record<string, string>>\n}\n\n/** The versions this release is built and tested against, from its own manifest. */\nexport interface Versions {\n readonly plus: string\n readonly effect: string\n readonly foldkit: string\n}\n\nexport interface SetupInput {\n readonly project: Option.Option<Project>\n readonly manager: Manager\n readonly versions: Versions\n}\n\nconst SITE = 'https://foldkit-plus.pages.dev'\nconst REPOSITORY = 'https://github.com/doeixd/foldkit-plus'\n\n/**\n * The `create-foldkit-app` release whose templates pin the Foldkit this\n * release needs (0.39.1 installs `foldkit` 0.168.0). A release that moves\n * the `foldkit` peer moves this with it.\n */\nexport const SCAFFOLDER = 'create-foldkit-app@0.39.1'\n\nconst GREENFIELD = `${REPOSITORY}/blob/main/skills/foldkit-plus/references/greenfield.md`\n\n/** What each job needs, where to import it from, and where it is explained. */\nexport const jobs: ReadonlyArray<{\n readonly job: string\n readonly imports: ReadonlyArray<string>\n readonly guide: string\n}> = [\n {\n job: 'Name what a feature may read and which Messages it may send',\n imports: ['surface', 'metadata'],\n guide: 'surface',\n },\n {\n job: 'A reusable Submodel placed several times, every part wired',\n imports: ['bundle', 'bundle-surface'],\n guide: 'bundle',\n },\n {\n job: 'Restyle or extend views from outside, through typed slots',\n imports: ['mixins', 'mixins-surface', 'mixins-ui'],\n guide: 'mixins',\n },\n {\n job: 'Media queries, timers, sockets, clipboard, undo history',\n imports: ['primitives'],\n guide: 'primitives',\n },\n {\n job: 'Declare the domain once: entities, relations, queries',\n imports: ['entity'],\n guide: 'entity',\n },\n {\n job: 'Server-owned data in the Model: queries, mutations, live updates',\n imports: ['remote', 'remote-server', 'remote-drizzle'],\n guide: 'remote',\n },\n {\n job: 'Edits that survive offline and converge across devices',\n imports: ['sync', 'durable'],\n guide: 'sync',\n },\n { job: 'Who may do what, enforced on every seam', imports: ['guard'], guide: 'guard' },\n {\n job: 'Who is signed in: a Yielded Auth session as the principal',\n imports: ['auth'],\n guide: 'auth',\n },\n {\n job: 'A slice of the Model kept in the URL or in storage',\n imports: ['mirror'],\n guide: 'mirror',\n },\n {\n job: 'Forms: drafts, validation, a decoded value, and dates, times and addresses in them',\n imports: ['form', 'mixins-form', 'form-recipes'],\n guide: 'form',\n },\n {\n job: 'Edit, create and list screens over Remote',\n imports: ['crud', 'mixins-crud'],\n guide: 'crud',\n },\n {\n job: 'An interactive data grid over rows you own',\n imports: ['data-grid', 'mixins-data-grid'],\n guide: 'data-grid',\n },\n {\n job: 'Drafts, revisions and publishing for content',\n imports: ['cms', 'cms-drizzle'],\n guide: 'cms',\n },\n {\n job: 'Pages as data, and a builder that edits them',\n imports: ['composition', 'builder', 'mixins-builder'],\n guide: 'composition',\n },\n {\n job: 'Rich text: the document, its editor, Markdown and code',\n imports: [\n 'richtext',\n 'richtext-dom',\n 'mixins-richtext',\n 'richtext-markdown',\n 'richtext-code',\n 'richtext-code-shiki',\n ],\n guide: 'richtext',\n },\n { job: 'Server rendering that hands the Model over', imports: ['ssr'], guide: 'ssr' },\n {\n job: 'Responsive images, their variants and placeholders, and icons as data',\n imports: ['media'],\n guide: 'media',\n },\n { job: 'Route topology as data: nodes, typed targets, titles', imports: ['site'], guide: 'site' },\n {\n job: 'What an AI agent may see and do, over MCP, WebMCP, A2A or Agent Native',\n imports: ['agent', 'agent-mcp', 'agent-webmcp', 'agent-a2a', 'agent-native'],\n guide: 'agent',\n },\n {\n job: 'React components in a Foldkit view, or Foldkit inside React',\n imports: ['react', 'react-codegen'],\n guide: 'react',\n },\n]\n\n/**\n * The packages `foldkit-plus` does not install, since each needs a library of\n * its own, and that library. `test/setup.test.ts` holds this to the manifest.\n */\nexport const adapters: ReadonlyArray<{\n readonly name: string\n readonly libraries: ReadonlyArray<string>\n readonly when: string\n}> = [\n {\n name: 'foldkit-agent-native',\n libraries: ['@agent-native/core'],\n when: 'agents through Agent Native',\n },\n {\n name: 'foldkit-auth',\n libraries: ['@yielded/auth'],\n when: 'sign-in and sessions with Yielded Auth',\n },\n { name: 'foldkit-cms-drizzle', libraries: ['drizzle-orm'], when: \"the CMS's server on Drizzle\" },\n {\n name: 'foldkit-mixins-ui',\n libraries: ['@foldkit/ui'],\n when: 'styling `@foldkit/ui` components through slots',\n },\n { name: 'foldkit-react', libraries: ['react', 'react-dom'], when: 'React interop' },\n {\n name: 'foldkit-react-codegen',\n libraries: ['typescript'],\n when: 'compiling Foldkit views to React TSX (a dev dependency)',\n },\n {\n name: 'foldkit-remote-drizzle',\n libraries: ['drizzle-orm'],\n when: 'answering Remote reads with Drizzle',\n },\n {\n name: 'foldkit-richtext-code-shiki',\n libraries: ['shiki'],\n when: 'highlighting code blocks with Shiki',\n },\n]\n\n/** The command that adds `packages` with `manager`. */\nexport const addCommand = (manager: Manager, packages: ReadonlyArray<string>): string =>\n `${manager} ${manager === 'npm' ? 'install' : 'add'} ${packages.join(' ')}`\n\n/** The major version a range asks for: `^4.0.0`, `~4.1`, `4.0.0-beta.1` all ask for 4. */\nconst majorOf = (range: string): Option.Option<number> =>\n Option.fromNullishOr(/(\\d+)/.exec(range)?.[1]).pipe(Option.map(Number))\n\n/** What the project has of a library against what this release needs, as a line to act on. */\nconst finding = (project: Project, library: string, wanted: string): string =>\n Option.match(Option.fromNullishOr(project.versions[library]), {\n onNone: () => `- \\`${library}\\` is not installed: step 2 adds \\`${library}@${wanted}\\`.`,\n onSome: range => {\n // Foldkit is 0.x, where a minor version breaks; Effect is past 1.\n const matches =\n library === 'foldkit'\n ? range.replace(/^[\\^~=v]*/, '').startsWith(wanted.split('.').slice(0, 2).join('.'))\n : Option.getOrUndefined(majorOf(range)) === Option.getOrUndefined(majorOf(wanted))\n return matches\n ? `- \\`${library}\\` ${range}: fits.`\n : `- \\`${library}\\` is ${range}, and Foldkit Plus needs ${wanted}: step 2 moves it to ${wanted}. Check the application builds after.`\n },\n })\n\nexport const setupGuide = ({ project, manager, versions }: SetupInput): string => {\n const install = addCommand(manager, [\n `effect@${versions.effect}`,\n `foldkit@${versions.foldkit}`,\n `@effect/platform-browser@${versions.effect}`,\n 'foldkit-plus',\n ])\n const check = Option.match(project, {\n onNone: () => [\n 'There is no `package.json` here: this is a new application. Do not scaffold yet. Follow the greenfield guide, which asks the user about the goals, the look and the domain before any code:',\n '',\n `- ${GREENFIELD} (in the skill of step 3, \\`references/greenfield.md\\`)`,\n '',\n 'When its first step has a name and a rendering mode, it scaffolds with:',\n '',\n '```bash',\n `npx ${SCAFFOLDER} --name <name> --rendering <spa|ssg|ssr> --example counter --package-manager ${manager}`,\n '```',\n '',\n 'Then run `npx foldkit-plus setup` again in the new folder and continue from step 2.',\n ],\n onSome: found => [\n `This is \\`${found.name}\\`, installed with ${manager}.`,\n '',\n finding(found, 'effect', versions.effect),\n finding(found, 'foldkit', versions.foldkit),\n ],\n })\n return [\n `# Foldkit Plus ${versions.plus}: setup`,\n '',\n 'Instructions for a coding agent, in order. Each step says what to run and why. Tell the user what you did at the end.',\n '',\n '## What these are',\n '',\n '- **Effect** (https://effect.website): TypeScript for typed effects, errors, schemas and streams. Foldkit Plus targets Effect 4.',\n '- **Foldkit** (https://foldkit.dev): an application is one state machine on Effect, a Schema-typed `Model`, a `Message` union and one pure `update`; I/O runs in Commands and Subscriptions.',\n '- **Foldkit Plus**: packages that extend a Foldkit application to agents, servers, other devices, the URL and design systems without a second place to keep state. An agent sends only Messages `update` already handles; server data lives in the Model; replicas replay the same Messages; the URL mirrors a slice of the Model.',\n '',\n '## 1. Check the project',\n '',\n ...check,\n '',\n '## 2. Install',\n '',\n '```bash',\n install,\n '```',\n '',\n '`foldkit-plus` brings every package except the adapters below, each of which needs a library of its own. Add one only when the application needs it:',\n '',\n ...adapters.map(\n each => `- ${each.when}: \\`${addCommand(manager, [each.name, ...each.libraries])}\\``,\n ),\n '',\n '## 3. Add the agent skill',\n '',\n '```bash',\n 'npx skills add doeixd/foldkit-plus --skill foldkit-plus',\n '```',\n '',\n 'It teaches you which package owns which kind of state, when to reach for each, and a working example of each. Read its `SKILL.md` before writing code with Foldkit Plus, and the reference for the package at hand before changing it.',\n // An empty folder was sent to the guide in step 1.\n ...Option.match(project, {\n onNone: () => [],\n onSome: () => [\n '',\n `Building a new application rather than extending one? Follow its \\`references/greenfield.md\\` (${GREENFIELD}): goals and the look, then the domain with the user, recorded in the project and mapped to these packages, then a plan for architecture, performance, SEO, testing, CI and deployment, before implementing.`,\n ],\n }),\n '',\n '## 4. Import',\n '',\n 'The namespaces most applications use come from the root:',\n '',\n '```ts',\n \"import { Surface, Projection, Remote, Sync, Mirror, Agent, Style } from 'foldkit-plus'\",\n '```',\n '',\n 'Everything else is a subpath named for its package, for example `foldkit-plus/remote-server` on the server, `foldkit-plus/sync/journal`, `foldkit-plus/mixins/theme`. Pick a package by who owns the data:',\n '',\n '| Job | Import from | Guide |',\n '| --- | --- | --- |',\n ...jobs.map(\n each =>\n `| ${each.job} | ${each.imports.map(name => `\\`foldkit-plus/${name}\\``).join(', ')} | ${SITE}/${each.guide} |`,\n ),\n '',\n '## 5. Rules every package keeps',\n '',\n '- One owner per datum: never keep a fact in the Model and again in a cache, a URL store or a second reducer.',\n '- Behaviour goes through Messages and `update`; agents, replicas and Behaviors never change the Model directly.',\n '- Rendering performs no I/O: fetching, syncing and mirroring run in Commands and Subscriptions.',\n '- Absence is an Effect `Option`, not `null`, except at a JSON, database or DOM boundary.',\n '',\n '## More',\n '',\n `- Guides and API: ${SITE}`,\n `- Demos: ${SITE}/demos`,\n `- Source and changelog: ${REPOSITORY}`,\n '',\n ].join('\\n')\n}\n"],"mappings":";;;;;;;AA6BA,MAAM,OAAO;AACb,MAAM,aAAa;;;;;;AAOnB,MAAa,aAAa;AAE1B,MAAM,aAAa,GAAG,WAAW;;AAGjC,MAAa,OAIR;CACH;EACE,KAAK;EACL,SAAS,CAAC,WAAW,UAAU;EAC/B,OAAO;CACT;CACA;EACE,KAAK;EACL,SAAS,CAAC,UAAU,gBAAgB;EACpC,OAAO;CACT;CACA;EACE,KAAK;EACL,SAAS;GAAC;GAAU;GAAkB;EAAW;EACjD,OAAO;CACT;CACA;EACE,KAAK;EACL,SAAS,CAAC,YAAY;EACtB,OAAO;CACT;CACA;EACE,KAAK;EACL,SAAS,CAAC,QAAQ;EAClB,OAAO;CACT;CACA;EACE,KAAK;EACL,SAAS;GAAC;GAAU;GAAiB;EAAgB;EACrD,OAAO;CACT;CACA;EACE,KAAK;EACL,SAAS,CAAC,QAAQ,SAAS;EAC3B,OAAO;CACT;CACA;EAAE,KAAK;EAA2C,SAAS,CAAC,OAAO;EAAG,OAAO;CAAQ;CACrF;EACE,KAAK;EACL,SAAS,CAAC,MAAM;EAChB,OAAO;CACT;CACA;EACE,KAAK;EACL,SAAS,CAAC,QAAQ;EAClB,OAAO;CACT;CACA;EACE,KAAK;EACL,SAAS;GAAC;GAAQ;GAAe;EAAc;EAC/C,OAAO;CACT;CACA;EACE,KAAK;EACL,SAAS,CAAC,QAAQ,aAAa;EAC/B,OAAO;CACT;CACA;EACE,KAAK;EACL,SAAS,CAAC,aAAa,kBAAkB;EACzC,OAAO;CACT;CACA;EACE,KAAK;EACL,SAAS,CAAC,OAAO,aAAa;EAC9B,OAAO;CACT;CACA;EACE,KAAK;EACL,SAAS;GAAC;GAAe;GAAW;EAAgB;EACpD,OAAO;CACT;CACA;EACE,KAAK;EACL,SAAS;GACP;GACA;GACA;GACA;GACA;GACA;EACF;EACA,OAAO;CACT;CACA;EAAE,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AAK,KAAK,IAAI,KAAK,KAAK,QAAQ,KAAI,SAAQ,kBAAkB,KAAK,GAAG,CAAC,CAAC,KAAK,IAAI,EAAE,KAAK,KAAK,GAAG,KAAK,MAAM,GAC/G;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,qBAAqB;EACrB,YAAY,KAAK;EACjB,2BAA2B;EAC3B;CACF,CAAC,CAAC,KAAK,IAAI;AACb"}
1
+ {"version":3,"file":"setup.mjs","names":[],"sources":["../src/setup.ts"],"sourcesContent":["/**\n * What `npx foldkit-plus setup` prints: instructions a coding agent can follow\n * in order, for the project it is run in. Pure: the CLI reads the project and\n * this package's manifest and passes them in, so a test can give any project.\n */\nimport { Option } from 'effect'\n\nexport type Manager = 'pnpm' | 'npm' | 'yarn' | 'bun'\n\n/** What the project's `package.json` says about the libraries Foldkit Plus needs. */\nexport interface Project {\n readonly name: string\n /** Each named library's version range, from any dependency field. */\n readonly versions: Readonly<Record<string, string>>\n /** Whether a `.gitattributes` applies here: in the project's folder or one above it in its repository. */\n readonly gitattributes: boolean\n /** Where pnpm reads this project's settings, which a workspace keeps at its root. */\n readonly pnpmSettings: PnpmSettings\n}\n\n/** A file pnpm reads settings from, in `folder` relative to the project (`.`, `../..`). */\nexport interface PnpmSettings {\n readonly folder: string\n readonly file: 'package.json' | 'pnpm-workspace.yaml'\n}\n\n/**\n * The versions this release is built and tested against, from its own\n * manifest: the workspace's Foldkit and Effect.\n */\nexport interface Versions {\n readonly plus: string\n readonly effect: string\n readonly foldkit: string\n}\n\nexport interface SetupInput {\n readonly project: Option.Option<Project>\n readonly manager: Manager\n readonly versions: Versions\n}\n\nconst SITE = 'https://foldkit-plus.pages.dev'\nconst REPOSITORY = 'https://github.com/doeixd/foldkit-plus'\n\n/**\n * The `create-foldkit-app` release whose templates pin the Foldkit this\n * release needs (0.41.0 installs `foldkit`, `@foldkit/ui` and `@foldkit/devtools`\n * 0.170.0, `@foldkit/vite-plugin` 0.29.0 and `effect` 4.1.0). A release that\n * moves the `foldkit` peer moves this with it.\n */\nexport const SCAFFOLDER = 'create-foldkit-app@0.41.0'\n\nconst GREENFIELD = `${REPOSITORY}/blob/main/skills/foldkit-plus/references/greenfield.md`\nconst AGENTS_BLOCK = `${REPOSITORY}/blob/main/skills/foldkit-plus/references/agents-md.md`\n\n/** What each job needs, where to import it from, and where it is explained. */\nexport const jobs: ReadonlyArray<{\n readonly job: string\n readonly imports: ReadonlyArray<string>\n readonly guide: string\n}> = [\n {\n job: 'Name what a feature may read and which Messages it may send',\n imports: ['surface', 'metadata'],\n guide: 'surface',\n },\n {\n job: 'A reusable Submodel placed several times, every part wired',\n imports: ['bundle', 'bundle-surface'],\n guide: 'bundle',\n },\n {\n job: 'Restyle or extend views from outside, through typed slots',\n imports: ['mixins', 'mixins-surface', 'mixins-ui'],\n guide: 'mixins',\n },\n {\n job: 'Media queries, timers, sockets, clipboard, undo history',\n imports: ['primitives'],\n guide: 'primitives',\n },\n {\n job: 'Declare the domain once: entities, relations, queries',\n imports: ['entity'],\n guide: 'entity',\n },\n {\n job: 'Server-owned data in the Model: queries, mutations, live updates',\n imports: ['remote', 'remote-server', 'remote-drizzle'],\n guide: 'remote',\n },\n {\n job: 'Edits that survive offline and converge across devices',\n imports: ['sync', 'durable'],\n guide: 'sync',\n },\n { job: 'Who may do what, enforced on every seam', imports: ['guard'], guide: 'guard' },\n {\n job: 'Who is signed in: a Yielded Auth session as the principal',\n imports: ['auth'],\n guide: 'auth',\n },\n {\n job: 'A slice of the Model kept in the URL or in storage',\n imports: ['mirror'],\n guide: 'mirror',\n },\n {\n job: 'Forms: drafts, validation, a decoded value, and dates, times and addresses in them',\n imports: ['form', 'mixins-form', 'form-recipes'],\n guide: 'form',\n },\n {\n job: 'Edit, create and list screens over Remote',\n imports: ['crud', 'mixins-crud'],\n guide: 'crud',\n },\n {\n job: 'An interactive data grid over rows you own',\n imports: ['data-grid', 'mixins-data-grid'],\n guide: 'data-grid',\n },\n {\n job: 'Drafts, revisions and publishing for content',\n imports: ['cms', 'cms-drizzle'],\n guide: 'cms',\n },\n {\n job: 'Pages as data, and a builder that edits them',\n imports: ['composition', 'builder', 'mixins-builder'],\n guide: 'composition',\n },\n {\n job: 'Rich text: the document, its editor, Markdown and code',\n imports: [\n 'richtext',\n 'richtext-dom',\n 'mixins-richtext',\n 'richtext-markdown',\n 'richtext-code',\n 'richtext-code-shiki',\n ],\n guide: 'richtext',\n },\n { job: 'Server rendering that hands the Model over', imports: ['ssr'], guide: 'ssr' },\n {\n job: 'Responsive images, their variants and placeholders, and icons as data',\n imports: ['media'],\n guide: 'media',\n },\n { job: 'Route topology as data: nodes, typed targets, titles', imports: ['site'], guide: 'site' },\n {\n job: 'What an AI agent may see and do, over MCP, WebMCP, A2A or Agent Native',\n imports: ['agent', 'agent-mcp', 'agent-webmcp', 'agent-a2a', 'agent-native'],\n guide: 'agent',\n },\n {\n job: 'React components in a Foldkit view, or Foldkit inside React',\n imports: ['react', 'react-codegen'],\n guide: 'react',\n },\n]\n\n/**\n * The packages `foldkit-plus` does not install, since each needs a library of\n * its own, and that library at the range the adapter peers on: a manager\n * given a bare name installs the `latest` tag, which for `@yielded/auth` is a\n * beta older than the one `foldkit-auth` names. `test/generated.test.ts`\n * holds this to the manifests.\n */\nexport const adapters: ReadonlyArray<{\n readonly name: string\n readonly libraries: ReadonlyArray<string>\n readonly when: string\n}> = [\n {\n name: 'foldkit-agent-native',\n libraries: ['@agent-native/core@0.214.0'],\n when: 'agents through Agent Native',\n },\n {\n name: 'foldkit-auth',\n libraries: ['@yielded/auth@0.1.0-beta.47'],\n when: 'sign-in and sessions with Yielded Auth',\n },\n {\n name: 'foldkit-cms-drizzle',\n libraries: ['drizzle-orm@1.0.0-rc.5'],\n when: \"the CMS's server on Drizzle\",\n },\n {\n name: 'foldkit-mixins-ui',\n libraries: ['@foldkit/ui@^0.170.0'],\n when: 'styling `@foldkit/ui` components through slots',\n },\n {\n name: 'foldkit-react',\n libraries: ['react@^19.0.0', 'react-dom@^19.0.0'],\n when: 'React interop',\n },\n {\n name: 'foldkit-react-codegen',\n libraries: ['typescript@>=5.7.2 <7'],\n when: 'compiling Foldkit views to React TSX (a dev dependency)',\n },\n {\n name: 'foldkit-remote-drizzle',\n libraries: ['drizzle-orm@1.0.0-rc.5'],\n when: 'answering Remote reads with Drizzle',\n },\n {\n name: 'foldkit-richtext-code-shiki',\n libraries: ['shiki@^4.4.3'],\n when: 'highlighting code blocks with Shiki',\n },\n]\n\n/**\n * The Effect packages an application meets that something names at a version\n * of its own: Foldkit's peers and its Vite plugin's dependencies name one\n * minor (`~4.1.0`), and each `@effect/*` package peers on an `effect` at least\n * its own version. Setup holds all of them at the Effect this release is\n * tested on, as `pnpm-workspace.yaml` does here (`test/generated.test.ts`\n * keeps the two lists together).\n */\nexport const effectPackages: ReadonlyArray<string> = [\n 'effect',\n '@effect/platform-browser',\n '@effect/platform-node',\n '@effect/platform-node-shared',\n '@effect/sql-sqlite-node',\n]\n\n/** Where the pins go, and the block that holds them. */\ninterface Pins {\n /** The file, as the step names it: `package.json`, `../../pnpm-workspace.yaml`. */\n readonly file: string\n readonly language: 'json' | 'yaml'\n readonly text: string\n}\n\n/** A YAML key, quoted where `@` would start something else. */\nconst yamlKey = (key: string) => (key.startsWith('@') ? `'${key}'` : key)\n\n/**\n * The settings that hold every Effect package at `effect`, to merge into the\n * file the manager reads them from. npm applies an override to a package the\n * project depends on only where the project names that same version, so its\n * block sets those dependencies too (a `$name` reference would follow them,\n * but npm 10 cannot resolve a scoped one); pnpm reads them only at a\n * workspace's root.\n */\nconst pinsOf = (\n manager: Manager,\n effect: string,\n direct: ReadonlySet<string>,\n pnpmSettings: PnpmSettings,\n): Pins => {\n const pins = Object.fromEntries(effectPackages.map(name => [name, effect]))\n const allowedVersions = { effect, '@effect/platform-browser': effect }\n if (manager === 'pnpm' && pnpmSettings.file === 'pnpm-workspace.yaml') {\n const lines = (entries: Readonly<Record<string, string>>, indent: string) =>\n Object.entries(entries).map(([name, version]) => `${indent}${yamlKey(name)}: ${version}`)\n return {\n file: `${pnpmSettings.folder}/pnpm-workspace.yaml`,\n language: 'yaml',\n text: [\n 'overrides:',\n ...lines(pins, ' '),\n 'peerDependencyRules:',\n ' allowedVersions:',\n ...lines(allowedVersions, ' '),\n ].join('\\n'),\n }\n }\n const fields = {\n npm: {\n dependencies: Object.fromEntries(\n effectPackages.filter(name => direct.has(name)).map(name => [name, effect]),\n ),\n overrides: pins,\n },\n pnpm: { pnpm: { overrides: pins, peerDependencyRules: { allowedVersions } } },\n yarn: { resolutions: pins },\n bun: { overrides: pins },\n }[manager]\n return {\n file:\n manager === 'pnpm' && pnpmSettings.folder !== '.'\n ? `${pnpmSettings.folder}/package.json`\n : 'package.json',\n language: 'json',\n text: JSON.stringify(fields, null, 2),\n }\n}\n\n/** Why `manager` needs the pins, after \"first merge this into `package.json`\". */\nconst pinsWhy: Readonly<Record<Manager, string>> = {\n npm: 'npm refuses a peer it does not match, and `overrides` lets one in without turning every peer check off; it overrides a dependency of the project only at the version the project names, so the block sets those too',\n pnpm: \"`overrides` sets the version, and `peerDependencyRules` lets Foldkit's exact peers accept it\",\n yarn: \"`resolutions` sets the version; Yarn warns of Foldkit's exact peers, and installs\",\n bun: \"`overrides` sets the version; Bun warns of Foldkit's exact peers, and installs\",\n}\n\n/**\n * The command that adds `packages` with `manager`, at exactly the versions\n * named when `exact`. A range a shell would read (`^`, `>`, a space) is quoted.\n */\nexport const addCommand = (\n manager: Manager,\n packages: ReadonlyArray<string>,\n exact = false,\n): string =>\n [\n manager,\n manager === 'npm' ? 'install' : 'add',\n ...(exact ? [manager === 'npm' || manager === 'pnpm' ? '--save-exact' : '--exact'] : []),\n ...packages.map(spec => (/^[\\w@/.-]+$/.test(spec) ? spec : `\"${spec}\"`)),\n ].join(' ')\n\n/** The major version a range asks for: `^4.0.0`, `~4.1`, `4.0.0-beta.1` all ask for 4. */\nconst majorOf = (range: string): Option.Option<number> =>\n Option.fromNullishOr(/(\\d+)/.exec(range)?.[1]).pipe(Option.map(Number))\n\n/** What the project has of a library against what this release needs, as a line to act on. */\nconst finding = (project: Project, library: string, wanted: string): string =>\n Option.match(Option.fromNullishOr(project.versions[library]), {\n onNone: () => `- \\`${library}\\` is not installed: step 2 adds \\`${library}@${wanted}\\`.`,\n onSome: range => {\n // Foldkit is 0.x, where a minor version breaks; Effect is past 1.\n const matches =\n library === 'foldkit'\n ? range.replace(/^[\\^~=v]*/, '').startsWith(wanted.split('.').slice(0, 2).join('.'))\n : Option.getOrUndefined(majorOf(range)) === Option.getOrUndefined(majorOf(wanted))\n return matches\n ? `- \\`${library}\\` ${range}: fits.`\n : `- \\`${library}\\` is ${range}, and Foldkit Plus needs ${wanted}: step 2 moves it to ${wanted}. Check the application builds after.`\n },\n })\n\nexport const setupGuide = ({ project, manager, versions }: SetupInput): string => {\n // Every Effect package the project names moves with `effect`, so the pins hold.\n const listed = Option.match(project, {\n onNone: () => [],\n onSome: found => effectPackages.filter(name => found.versions[name] !== undefined),\n })\n const moved = new Set(['effect', '@effect/platform-browser', ...listed])\n const pins = pinsOf(\n manager,\n versions.effect,\n moved,\n Option.match(project, {\n onNone: () => ({ folder: '.', file: 'package.json' }),\n onSome: found => found.pnpmSettings,\n }),\n )\n // Foldkit's devtools peer on `@foldkit/ui` at any release, and a manager left\n // to pick one takes the newest, which may peer on a newer Effect (#229).\n const uiPeer = Option.exists(\n project,\n found =>\n found.versions['@foldkit/devtools'] !== undefined &&\n found.versions['@foldkit/ui'] === undefined,\n )\n // npm's block already names the Effect packages the project depends on.\n const install = addCommand(\n manager,\n [\n ...(manager === 'npm'\n ? []\n : effectPackages.filter(name => moved.has(name)).map(name => `${name}@${versions.effect}`)),\n `foldkit@${versions.foldkit}`,\n ...(uiPeer ? [`@foldkit/ui@${versions.foldkit}`] : []),\n 'foldkit-plus',\n ],\n true,\n )\n const check = Option.match(project, {\n onNone: () => [\n 'There is no `package.json` here: this is a new application. Do not scaffold yet. Follow the greenfield guide, which asks the user about the goals, the look and the domain before any code:',\n '',\n `- ${GREENFIELD} (in the skill of step 3, \\`references/greenfield.md\\`)`,\n '',\n `When its first step has a name and a rendering mode, it scaffolds with the command for that mode; \\`--example\\` is for spa alone, and an ssg or ssr scaffold refuses it${manager === 'npm' ? \". An ssg scaffold names `@foldkit/devtools` but not `@foldkit/ui`, its peer, so npm takes the newest `@foldkit/ui`, and refuses the install once that one needs a newer Effect than the scaffold's: `--force` lets it install with a warning, and step 2 replaces that `@foldkit/ui` with the one at the scaffold's Foldkit release (`--legacy-peer-deps` would also drop peers the scaffolder itself needs)\" : ''}:`,\n '',\n '```bash',\n `npx ${SCAFFOLDER} --name <name> --rendering spa --example counter --package-manager ${manager}`,\n `npx ${manager === 'npm' ? '--force ' : ''}${SCAFFOLDER} --name <name> --rendering ssg --package-manager ${manager}`,\n `npx ${SCAFFOLDER} --name <name> --rendering ssr --package-manager ${manager}`,\n '```',\n '',\n 'Then run `npx --legacy-peer-deps foldkit-plus setup` again in the new folder and continue from step 2.',\n ],\n onSome: found => [\n `This is \\`${found.name}\\`, installed with ${manager}.`,\n '',\n finding(found, 'effect', versions.effect),\n finding(found, 'foldkit', versions.foldkit),\n ...(uiPeer\n ? [\n `- \\`@foldkit/devtools\\` peers on \\`@foldkit/ui\\`, which the project does not name: step 2 adds \\`@foldkit/ui@${versions.foldkit}\\`, since a manager left to choose takes the newest, which may need a newer Effect.`,\n ]\n : []),\n // Never overwritten: line endings are the project's to choose once chosen.\n ...(found.gitattributes\n ? ['- `.gitattributes` is there: leave it as it is.']\n : [\n \"- There is no `.gitattributes`. Write one at the repository's root (beside `package.json` if this is not yet a repository), so Git keeps the LF line endings the formatter writes and `git add` on Windows does not warn of every file:\",\n '',\n '```gitattributes',\n '* text=auto eol=lf',\n '*.wasm binary',\n '```',\n ]),\n ],\n })\n return [\n `# Foldkit Plus ${versions.plus}: setup`,\n '',\n 'Instructions for a coding agent, in order. Each step says what to run and why. Tell the user what you did at the end.',\n '',\n '## What these are',\n '',\n '- **Effect** (https://effect.website): TypeScript for typed effects, errors, schemas and streams. Foldkit Plus targets Effect 4.',\n '- **Foldkit** (https://foldkit.dev): an application is one state machine on Effect, a Schema-typed `Model`, a `Message` union and one pure `update`; I/O runs in Commands and Subscriptions.',\n '- **Foldkit Plus**: packages that extend a Foldkit application to agents, servers, other devices, the URL and design systems without a second place to keep state. An agent sends only Messages `update` already handles; server data lives in the Model; replicas replay the same Messages; the URL mirrors a slice of the Model.',\n '',\n '## 1. Check the project',\n '',\n ...check,\n '',\n '## 2. Install',\n '',\n `Foldkit and its tooling name one Effect release exactly, and Foldkit Plus is tested on ${versions.effect}. To install one copy of each Effect package, at that release, first merge this into \\`${pins.file}\\`, keeping what it holds (${pinsWhy[manager]}${pins.file === 'package.json' ? '' : '; pnpm reads them only at the workspace root'}):`,\n '',\n `\\`\\`\\`${pins.language}`,\n pins.text,\n '```',\n '',\n 'Then install:',\n '',\n '```bash',\n install,\n '```',\n '',\n '`foldkit-plus` brings every package except the adapters below, each of which needs a library of its own. Add one only when the application needs it:',\n '',\n ...adapters.map(\n each => `- ${each.when}: \\`${addCommand(manager, [each.name, ...each.libraries])}\\``,\n ),\n '',\n '## 3. Add the agent skill',\n '',\n '```bash',\n 'npx skills add doeixd/foldkit-plus --skill foldkit-plus',\n '```',\n '',\n 'It teaches you which package owns which kind of state, when to reach for each, and a working example of each. Read its `SKILL.md` before writing code with Foldkit Plus, and the reference for the package at hand before changing it. To look one symbol or topic up in the docs of the versions installed here, run `npx foldkit-plus docs <symbol or words>` (`--list` for what there is).',\n // An empty folder was sent to the guide in step 1.\n ...Option.match(project, {\n onNone: () => [],\n onSome: () => [\n '',\n `Paste the block in its \\`references/agents-md.md\\` (${AGENTS_BLOCK}) under Project Notes in the project's \\`AGENTS.md\\`: the house rules and known traps for an application on these packages.`,\n '',\n `Building a new application rather than extending one? Follow its \\`references/greenfield.md\\` (${GREENFIELD}): goals and the look, then the domain with the user, recorded in the project and mapped to these packages, then a plan for architecture, performance, SEO, testing, CI and deployment, before implementing.`,\n ],\n }),\n '',\n '## 4. Import',\n '',\n 'The namespaces most applications use come from the root:',\n '',\n '```ts',\n \"import { Surface, Projection, Remote, Sync, Mirror, Agent, Style } from 'foldkit-plus'\",\n '```',\n '',\n 'Everything else is a subpath named for its package, for example `foldkit-plus/remote-server` on the server, `foldkit-plus/sync/journal`, `foldkit-plus/mixins/theme`. Pick a package by who owns the data:',\n '',\n '| Job | Import from | Guide |',\n '| --- | --- | --- |',\n ...jobs.map(\n each =>\n `| ${each.job} | ${each.imports.map(name => `\\`foldkit-plus/${name}\\``).join(', ')} | ${SITE}/${each.guide} |`,\n ),\n '',\n '## 5. Rules every package keeps',\n '',\n '- One owner per datum: never keep a fact in the Model and again in a cache, a URL store or a second reducer.',\n '- Behaviour goes through Messages and `update`; agents, replicas and Behaviors never change the Model directly.',\n '- Rendering performs no I/O: fetching, syncing and mirroring run in Commands and Subscriptions.',\n '- Absence is an Effect `Option`, not `null`, except at a JSON, database or DOM boundary.',\n '',\n '## More',\n '',\n `- Guides and API: ${SITE}`,\n `- Demos: ${SITE}/demos`,\n `- Source and changelog: ${REPOSITORY}`,\n '',\n ].join('\\n')\n}\n"],"mappings":";;;;;;;AA0CA,MAAM,OAAO;AACb,MAAM,aAAa;;;;;;;AAQnB,MAAa,aAAa;AAE1B,MAAM,aAAa,GAAG,WAAW;AACjC,MAAM,eAAe,GAAG,WAAW;;AAGnC,MAAa,OAIR;CACH;EACE,KAAK;EACL,SAAS,CAAC,WAAW,UAAU;EAC/B,OAAO;CACT;CACA;EACE,KAAK;EACL,SAAS,CAAC,UAAU,gBAAgB;EACpC,OAAO;CACT;CACA;EACE,KAAK;EACL,SAAS;GAAC;GAAU;GAAkB;EAAW;EACjD,OAAO;CACT;CACA;EACE,KAAK;EACL,SAAS,CAAC,YAAY;EACtB,OAAO;CACT;CACA;EACE,KAAK;EACL,SAAS,CAAC,QAAQ;EAClB,OAAO;CACT;CACA;EACE,KAAK;EACL,SAA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;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,GAAG;EACH;EACA;EACA;EACA,0FAA0F,SAAS,OAAO,yFAAyF,KAAK,KAAK,6BAA6B,QAAQ,WAAW,KAAK,SAAS,iBAAiB,KAAK,+CAA+C;EAChV;EACA,SAAS,KAAK;EACd,KAAK;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,GAAG,SAAS,KACV,SAAQ,KAAK,KAAK,KAAK,MAAM,WAAW,SAAS,CAAC,KAAK,MAAM,GAAG,KAAK,SAAS,CAAC,EAAE,GACnF;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EAEA,GAAG,OAAO,MAAM,SAAS;GACvB,cAAc,CAAC;GACf,cAAc;IACZ;IACA,uDAAuD,aAAa;IACpE;IACA,kGAAkG,WAAW;GAC/G;EACF,CAAC;EACD;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,GAAG,KAAK,KACN,SACE,KAAK,KAAK,IAAI,KAAK,KAAK,QAAQ,KAAI,SAAQ,kBAAkB,KAAK,GAAG,CAAC,CAAC,KAAK,IAAI,EAAE,KAAK,KAAK,GAAG,KAAK,MAAM,GAC/G;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,qBAAqB;EACrB,YAAY,KAAK;EACjB,2BAA2B;EAC3B;CACF,CAAC,CAAC,KAAK,IAAI;AACb"}
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Loads an optional peer of a `foldkit-plus/testing` subpath on first use, so
3
+ * importing the subpath loads nothing an application has not installed, and a
4
+ * missing peer says what to install instead of Node's bare "Cannot find
5
+ * package". Internal: not an export of `foldkit-plus`.
6
+ */
7
+ export declare const peer: <Module>(subpath: string, name: string, load: () => Promise<Module>) => Promise<Module>;
8
+ //# sourceMappingURL=peer.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"peer.d.mts","names":[],"sources":["../../src/testing/peer.ts"],"mappings":";;;;;;qBAMa,OAAc,QAAM,iBAChB,cACH,YACA,QAAQ,YACnB,QAAQ"}
@@ -0,0 +1,19 @@
1
+ // src/testing/peer.ts
2
+ /**
3
+ * Loads an optional peer of a `foldkit-plus/testing` subpath on first use, so
4
+ * importing the subpath loads nothing an application has not installed, and a
5
+ * missing peer says what to install instead of Node's bare "Cannot find
6
+ * package". Internal: not an export of `foldkit-plus`.
7
+ */
8
+ const peer = async (subpath, name, load) => {
9
+ try {
10
+ return await load();
11
+ } catch (error) {
12
+ if (!isMissing(error, name)) throw error;
13
+ throw new Error(`foldkit-plus/${subpath} needs \`${name}\`, which is not installed. Add it as a dev dependency: pnpm add -D ${name}`, { cause: error });
14
+ }
15
+ };
16
+ const isMissing = (error, name) => error instanceof Error && "code" in error && error.code === "ERR_MODULE_NOT_FOUND" && error.message.includes(`'${name}'`);
17
+ export { peer };
18
+
19
+ //# sourceMappingURL=peer.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"peer.mjs","names":[],"sources":["../../src/testing/peer.ts"],"sourcesContent":["/**\n * Loads an optional peer of a `foldkit-plus/testing` subpath on first use, so\n * importing the subpath loads nothing an application has not installed, and a\n * missing peer says what to install instead of Node's bare \"Cannot find\n * package\". Internal: not an export of `foldkit-plus`.\n */\nexport const peer = async <Module>(\n subpath: string,\n name: string,\n load: () => Promise<Module>,\n): Promise<Module> => {\n try {\n return await load()\n } catch (error) {\n if (!isMissing(error, name)) throw error\n throw new Error(\n `foldkit-plus/${subpath} needs \\`${name}\\`, which is not installed. ` +\n `Add it as a dev dependency: pnpm add -D ${name}`,\n { cause: error },\n )\n }\n}\n\n// Node and Vitest both say `Cannot find package 'name'`. A package that is\n// installed but fails to load names something else, and is rethrown as it is.\nconst isMissing = (error: unknown, name: string): boolean =>\n error instanceof Error &&\n 'code' in error &&\n error.code === 'ERR_MODULE_NOT_FOUND' &&\n error.message.includes(`'${name}'`)\n"],"mappings":";;;;;;;AAMA,MAAa,OAAO,OAClB,SACA,MACA,SACoB;CACpB,IAAI;EACF,OAAO,MAAM,KAAK;CACpB,SAAS,OAAO;EACd,IAAI,CAAC,UAAU,OAAO,IAAI,GAAG,MAAM;EACnC,MAAM,IAAI,MACR,gBAAgB,QAAQ,WAAW,KAAK,sEACK,QAC7C,EAAE,OAAO,MAAM,CACjB;CACF;AACF;AAIA,MAAM,aAAa,OAAgB,SACjC,iBAAiB,SACjB,UAAU,SACV,MAAM,SAAS,0BACf,MAAM,QAAQ,SAAS,IAAI,KAAK,EAAE"}
@@ -0,0 +1,49 @@
1
+ import { Duration } from "effect";
2
+ import { Locator, Page } from "playwright";
3
+ export interface OptimisticOptions {
4
+ /** The user's action that writes: a click, a key. */
5
+ readonly act: () => Promise<unknown>;
6
+ /** What the page shows once the write is made. */
7
+ readonly shows: Locator;
8
+ /** How long each Remote mutation is held at the network. `'3 seconds'` unless given. */
9
+ readonly hold?: Duration.Input;
10
+ /** How soon after `act` begins `shows` must show, while every write is held. `'1 second'` unless given. */
11
+ readonly within?: Duration.Input;
12
+ }
13
+ /**
14
+ * The write shows before the server answers, and still shows once it has.
15
+ * Every Remote mutation the page sends is held at the network for `hold`;
16
+ * `shows` must be visible within `within` of `act` while they are held, and
17
+ * again after every answer has landed and been drawn. Throws otherwise, and
18
+ * when `act` sent no Remote mutation, since nothing was then held.
19
+ */
20
+ declare const optimistic: (page: Page, options: OptimisticOptions) => Promise<void>;
21
+ export interface NeverShowsOptions {
22
+ /** What the page must not show at any moment of `during`. */
23
+ readonly text: string | RegExp;
24
+ /**
25
+ * The steps to watch: a reload, a navigation away and back. End it on what
26
+ * the page waits for (an answer, a row), since watching stops once it ends
27
+ * and the page is quiet.
28
+ */
29
+ readonly during: () => Promise<unknown>;
30
+ }
31
+ /**
32
+ * The page never shows `text` while `during` runs, nor until the page is
33
+ * quiet after it: a cached page revisited never reads "Loading…", even for
34
+ * one frame. Throws with the line that showed.
35
+ */
36
+ declare const neverShows: (page: Page, options: NeverShowsOptions) => Promise<void>;
37
+ /**
38
+ * Collects every error the page logs (`console.error`) and every exception it
39
+ * does not catch, from now until the page closes. Read the list at the end.
40
+ */
41
+ declare const consoleErrors: (page: Page) => (() => ReadonlyArray<string>);
42
+ /** Assertions on what a running page shows, for Playwright. */
43
+ export declare const Behaviors: {
44
+ readonly optimistic: typeof optimistic;
45
+ readonly neverShows: typeof neverShows;
46
+ readonly consoleErrors: typeof consoleErrors;
47
+ };
48
+ export {};
49
+ //# sourceMappingURL=playwright.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"playwright.d.mts","names":[],"sources":["../../src/testing/playwright.ts"],"mappings":";;iBAgEiB;;WAEN,WAAW;;WAEX,OAAO;;WAEP,OAAO,SAAS;;WAEhB,SAAS,SAAS;;;;;;;;;cAUvB,aAAU,MAAgB,MAAI,SAAW,sBAAoB;iBAmDlD;;WAEN,eAAe;;;;;;WAMf,cAAc;;;;;;;cA2CnB,aAAU,MAAgB,MAAI,SAAW,sBAAoB;;;;;cA6B7D,gBAAa,MAAU,gBAAc;;qBAU9B"}
@@ -0,0 +1,171 @@
1
+ import { Duration, Option, Schema } from "effect";
2
+ import { RemoteJsonRequest } from "foldkit-remote";
3
+ // src/testing/playwright.ts
4
+ /**
5
+ * `foldkit-plus/testing/playwright`: what a user sees, asserted on a running
6
+ * page. A write shows before the server answers and stays after it; a step
7
+ * never shows a given text, at any moment; the page logs no error.
8
+ *
9
+ * Each checks the page as drawn, over the real network: it proves that the
10
+ * whole application (server, hydration, persistence, the Worker) delivers a
11
+ * property. Which Message breaks a read's property is
12
+ * `foldkit-plus/remote/testing`'s `Trace`, which records every Model without
13
+ * a browser; reach for it once one of these fails.
14
+ *
15
+ * Playwright is an optional peer of `foldkit-plus`, needed only for its types:
16
+ * this module calls nothing but the `Page` it is given.
17
+ */
18
+ const decodeRequest = Schema.decodeUnknownOption(Schema.fromJsonString(RemoteJsonRequest));
19
+ /** A Remote mutation over HTTP, by the JSON request `Remote.http` sends. */
20
+ const isRemoteMutation = (request) => {
21
+ const body = request.postData();
22
+ return request.method() === "POST" && body !== null && Option.exists(decodeRequest(body), (sent) => sent.operation === "mutate");
23
+ };
24
+ const millis = (input) => Duration.toMillis(Duration.fromInputUnsafe(input));
25
+ /**
26
+ * Resolves once three frames in a row pass with no change to the document,
27
+ * or after two seconds of changes: a Message an answer caused has been drawn.
28
+ */
29
+ const quiet = (page) => page.evaluate(() => new Promise((resolve) => {
30
+ let calm = 0;
31
+ const observer = new MutationObserver(() => {
32
+ calm = 0;
33
+ });
34
+ const done = () => {
35
+ observer.disconnect();
36
+ resolve();
37
+ };
38
+ observer.observe(document, {
39
+ childList: true,
40
+ subtree: true,
41
+ characterData: true,
42
+ attributes: true
43
+ });
44
+ setTimeout(done, 2e3);
45
+ const frame = () => {
46
+ calm += 1;
47
+ if (calm >= 3) done();
48
+ else requestAnimationFrame(frame);
49
+ };
50
+ requestAnimationFrame(frame);
51
+ }));
52
+ /**
53
+ * The write shows before the server answers, and still shows once it has.
54
+ * Every Remote mutation the page sends is held at the network for `hold`;
55
+ * `shows` must be visible within `within` of `act` while they are held, and
56
+ * again after every answer has landed and been drawn. Throws otherwise, and
57
+ * when `act` sent no Remote mutation, since nothing was then held.
58
+ */
59
+ const optimistic = async (page, options) => {
60
+ const hold = millis(options.hold ?? "3 seconds");
61
+ const within = millis(options.within ?? "1 second");
62
+ if (within >= hold) throw new Error(`optimistic: within (${within} ms) must be shorter than hold (${hold} ms), or what shows could be the answer`);
63
+ const held = [];
64
+ const letThrough = async (route) => {
65
+ await new Promise((resume) => setTimeout(resume, hold));
66
+ await route.fallback();
67
+ };
68
+ const answered = async (request) => {
69
+ const response = await request.response();
70
+ if (response !== null) await response.finished();
71
+ };
72
+ const route = await page.route("**/*", (route, request) => {
73
+ if (!isRemoteMutation(request)) return route.fallback();
74
+ held.push(answered(request));
75
+ return letThrough(route);
76
+ });
77
+ const shows = String(options.shows);
78
+ try {
79
+ const started = Date.now();
80
+ await options.act();
81
+ await options.shows.waitFor({
82
+ state: "visible",
83
+ timeout: Math.max(1, within - (Date.now() - started))
84
+ }).catch((error) => {
85
+ throw new Error(`optimistic: ${shows} did not show within ${within} ms of the action`, { cause: error });
86
+ });
87
+ if (held.length === 0) throw new Error(`optimistic: ${shows} showed, but the action sent no Remote mutation`);
88
+ await Promise.all(held);
89
+ await quiet(page);
90
+ if (!await options.shows.isVisible()) throw new Error(`optimistic: ${shows} showed while the write was held, but not after its answer`);
91
+ } finally {
92
+ await route.dispose();
93
+ await Promise.allSettled(held);
94
+ }
95
+ };
96
+ const watchText = ({ key, source, flags }) => {
97
+ if (window !== window.top) return;
98
+ const pattern = new RegExp(source, flags);
99
+ let reported = false;
100
+ const check = () => {
101
+ if (reported) return;
102
+ const line = (document.body?.innerText ?? "").split("\n").find((each) => pattern.test(each));
103
+ if (line === void 0) return;
104
+ reported = true;
105
+ Reflect.apply(Reflect.get(window, key), void 0, [line]);
106
+ };
107
+ const observer = new MutationObserver(check);
108
+ observer.observe(document, {
109
+ childList: true,
110
+ subtree: true,
111
+ characterData: true,
112
+ attributes: true
113
+ });
114
+ Reflect.set(window, `${key}Stop`, () => observer.disconnect());
115
+ check();
116
+ };
117
+ const stopWatching = (key) => Reflect.apply(Reflect.get(window, `${key}Stop`), void 0, []);
118
+ /**
119
+ * The page never shows `text` while `during` runs, nor until the page is
120
+ * quiet after it: a cached page revisited never reads "Loading…", even for
121
+ * one frame. Throws with the line that showed.
122
+ */
123
+ const neverShows = async (page, options) => {
124
+ const key = `__foldkitNeverShows${crypto.randomUUID().replaceAll("-", "")}`;
125
+ const { text } = options;
126
+ const watch = typeof text === "string" ? {
127
+ key,
128
+ source: text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"),
129
+ flags: ""
130
+ } : {
131
+ key,
132
+ source: text.source,
133
+ flags: text.flags
134
+ };
135
+ const shown = [];
136
+ const binding = await page.exposeBinding(key, (_, line) => {
137
+ shown.push(line);
138
+ });
139
+ const script = await page.addInitScript(watchText, watch);
140
+ try {
141
+ await page.evaluate(watchText, watch);
142
+ await options.during();
143
+ await quiet(page);
144
+ } finally {
145
+ await script.dispose();
146
+ if (!page.isClosed()) await page.evaluate(stopWatching, key);
147
+ await binding.dispose();
148
+ }
149
+ if (shown.length > 0) throw new Error(`neverShows: the page showed ${String(text)}: "${shown[0]}"`);
150
+ };
151
+ /**
152
+ * Collects every error the page logs (`console.error`) and every exception it
153
+ * does not catch, from now until the page closes. Read the list at the end.
154
+ */
155
+ const consoleErrors = (page) => {
156
+ const errors = [];
157
+ page.on("console", (message) => {
158
+ if (message.type() === "error") errors.push(message.text());
159
+ });
160
+ page.on("pageerror", (error) => errors.push(String(error)));
161
+ return () => [...errors];
162
+ };
163
+ /** Assertions on what a running page shows, for Playwright. */
164
+ const Behaviors = {
165
+ optimistic,
166
+ neverShows,
167
+ consoleErrors
168
+ };
169
+ export { Behaviors };
170
+
171
+ //# sourceMappingURL=playwright.mjs.map
@@ -0,0 +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 and stays after it; a step\n * never shows a given text, at any moment; 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 { Locator, Page, Request, Route } from 'playwright'\n\nconst decodeRequest = Schema.decodeUnknownOption(Schema.fromJsonString(RemoteJsonRequest))\n\n/** A Remote mutation over HTTP, by the JSON request `Remote.http` sends. */\nconst isRemoteMutation = (request: Request): boolean => {\n const body = request.postData()\n return (\n request.method() === 'POST' &&\n body !== null &&\n Option.exists(decodeRequest(body), sent => sent.operation === 'mutate')\n )\n}\n\nconst millis = (input: Duration.Input) => Duration.toMillis(Duration.fromInputUnsafe(input))\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\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 /** How long each Remote mutation is held at the network. `'3 seconds'` unless given. */\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/**\n * The write shows before the server answers, and still shows once it has.\n * Every Remote mutation the page sends is held at the network for `hold`;\n * `shows` must be visible within `within` of `act` while they are held, and\n * again after every answer has landed and been drawn. Throws otherwise, and\n * when `act` sent no Remote mutation, since nothing was then held.\n */\nconst optimistic = async (page: Page, options: OptimisticOptions): Promise<void> => {\n const hold = millis(options.hold ?? '3 seconds')\n const within = millis(options.within ?? '1 second')\n if (within >= hold)\n throw new Error(\n `optimistic: within (${within} ms) must be shorter than hold (${hold} ms), ` +\n 'or what shows could be the answer',\n )\n const held: Array<Promise<void>> = []\n // Let through after `hold`. The answer is awaited apart from the handler:\n // Playwright passes a request on to the next handler only once this one returns.\n const letThrough = async (route: Route) => {\n await new Promise(resume => setTimeout(resume, hold))\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 (!isRemoteMutation(request)) return route.fallback()\n held.push(answered(request))\n return letThrough(route)\n })\n const shows = String(options.shows)\n try {\n const started = Date.now()\n await options.act()\n // A write is let through `hold` after it was sent, which was after `act`\n // began, so whatever shows by this deadline was drawn before any answer.\n await options.shows\n .waitFor({ state: 'visible', timeout: Math.max(1, within - (Date.now() - started)) })\n .catch((error: unknown) => {\n throw new Error(`optimistic: ${shows} did not show within ${within} ms of the action`, {\n cause: error,\n })\n })\n if (held.length === 0)\n throw new Error(`optimistic: ${shows} showed, but the action sent no Remote mutation`)\n await Promise.all(held)\n await quiet(page)\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 } finally {\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":";;;;;;;;;;;;;;;;;AAkBA,MAAM,gBAAgB,OAAO,oBAAoB,OAAO,eAAe,iBAAiB,CAAC;;AAGzF,MAAM,oBAAoB,YAA8B;CACtD,MAAM,OAAO,QAAQ,SAAS;CAC9B,OACE,QAAQ,OAAO,MAAM,UACrB,SAAS,QACT,OAAO,OAAO,cAAc,IAAI,IAAG,SAAQ,KAAK,cAAc,QAAQ;AAE1E;AAEA,MAAM,UAAU,UAA0B,SAAS,SAAS,SAAS,gBAAgB,KAAK,CAAC;;;;;AAM3F,MAAM,SAAS,SACb,KAAK,eAED,IAAI,SAAc,YAAW;CAC3B,IAAI,OAAO;CACX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AE,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"}
@@ -0,0 +1,103 @@
1
+ import { Plugin } from "esbuild";
2
+ import { WorkerHandle } from "wrangler";
3
+ export interface StackOptions {
4
+ /** The Worker's Wrangler configuration (`wrangler.toml`, `.json` or `.jsonc`). */
5
+ readonly wrangler: string;
6
+ /** The source esbuild bundles into what `main` names. */
7
+ readonly entry: string;
8
+ /**
9
+ * Local values for vars the deployed Worker is given elsewhere. As a
10
+ * function, of the origin the stack answers at: the Worker has them from
11
+ * its first request (`origin => ({ ORIGIN: origin })`).
12
+ */
13
+ readonly vars?: Vars | ((origin: string) => Vars);
14
+ /** Local values for secrets, over any in `.dev.vars`. */
15
+ readonly secrets?: Readonly<Record<string, string>>;
16
+ /** esbuild plugins for the bundle, the deploy's and the stack's alike. */
17
+ readonly plugins?: ReadonlyArray<Plugin>;
18
+ /**
19
+ * Whether each line the Worker writes to its console is printed here, by
20
+ * its level, as it arrives (`'print'`, the default). `logs()` keeps them either way.
21
+ */
22
+ readonly console?: 'print' | 'quiet';
23
+ }
24
+ type Vars = Readonly<Record<string, string>>;
25
+ /** A line the Worker wrote to its console. An `Error` logged carries its stack in `message`. */
26
+ export interface WorkerLog {
27
+ /** As workerd names it: `debug`, `info`, `log`, `warn` or `error`. */
28
+ readonly level: string;
29
+ readonly message: string;
30
+ readonly timestamp: number;
31
+ }
32
+ /**
33
+ * What a watched stack reports after each change to the bundle's sources or
34
+ * to the Wrangler configuration.
35
+ */
36
+ export interface WatchListener {
37
+ /** The new Worker answers at the same origin, over the same storage. */
38
+ readonly onSwap: () => void;
39
+ /**
40
+ * The change was not swapped in, and the Worker running keeps answering
41
+ * over the same storage. It did not build, built no code (as an entry saved
42
+ * in place reads for a moment), did not start when tried on a workerd of
43
+ * its own, or is a configuration the stack refuses. Or it was swapped in,
44
+ * and a D1 migration then failed on the running database; the message says so.
45
+ */
46
+ readonly onRefused: (message: string) => void;
47
+ /**
48
+ * A Worker that started when tried did not start in the stack. Wrangler's
49
+ * harness tears its runtime down with it, storage included, so the stack
50
+ * has stopped answering and watches no more: call `stop`, and start again.
51
+ */
52
+ readonly onStopped: (message: string) => void;
53
+ }
54
+ export interface Stack<Env> {
55
+ /** Where the Worker answers over real HTTP. */
56
+ readonly origin: string;
57
+ /**
58
+ * The Worker's bindings, as the Worker sees them. A swap retires the ones
59
+ * read before it (Miniflare's "poisoned stub"), so read them after.
60
+ */
61
+ readonly env: () => Promise<Env>;
62
+ /** A request straight to the Worker; an upgrade answers with its socket. */
63
+ readonly dispatch: WorkerHandle['fetch'];
64
+ /**
65
+ * Takes what the Worker wrote to its console since the last call, oldest
66
+ * first. The lines come from workerd beside the response, not on it, so a
67
+ * line written for a request may arrive after it: poll.
68
+ */
69
+ readonly logs: () => ReadonlyArray<WorkerLog>;
70
+ /**
71
+ * Rebuilds on every change to a file the bundle read, and rereads the
72
+ * Wrangler configuration when it changes. Each change is first started on
73
+ * a workerd of its own, then swapped in at the same origin, and the D1
74
+ * migrations not yet applied are applied. D1, R2 and Durable Object storage stay.
75
+ */
76
+ readonly watch: (listener: WatchListener) => Promise<void>;
77
+ /**
78
+ * Stops watching, stops workerd and removes the bundle's directory, each
79
+ * even when one before it failed. A change not yet being tried swaps
80
+ * nothing and reports nothing; one being tried finishes first. A second
81
+ * call returns the first one's promise.
82
+ */
83
+ readonly stop: () => Promise<void>;
84
+ }
85
+ /** Writes the bundle where `main` says, for `wrangler deploy`. */
86
+ declare const writeBundle: (options: Omit<StackOptions, 'vars' | 'secrets'>) => Promise<void>;
87
+ /**
88
+ * Starts the Worker with a fresh, migrated D1 for each `[[d1_databases]]`,
89
+ * and empty R2 and Durable Object storage. Each call is a stack of its own,
90
+ * so test files running side by side share nothing.
91
+ */
92
+ declare const start: <Env>(options: StackOptions) => Promise<Stack<Env>>;
93
+ /**
94
+ * The local Workers stack. `Stack.start` runs the Worker for tests and
95
+ * development; `Stack.writeBundle` writes what `wrangler deploy` uploads,
96
+ * bundled the same way.
97
+ */
98
+ export declare const Stack: {
99
+ readonly start: typeof start;
100
+ readonly writeBundle: typeof writeBundle;
101
+ };
102
+ export {};
103
+ //# sourceMappingURL=workers.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workers.d.mts","names":[],"sources":["../../src/testing/workers.ts"],"mappings":";;iBA8BiB;;WAEN;;WAEA;;;;;;WAMA,OAAO,SAAS,mBAAmB;;WAEnC,UAAU,SAAS;;WAEnB,UAAU,cAAc;;;;;WAKxB;;KAGN,OAAO,SAAS;;iBAGJ;;WAEN;WACA;WACA;;;;;;iBAOM;;WAEN;;;;;;;;WAQA,YAAY;;;;;;WAMZ,YAAY;;iBAGN,MAAM;;WAEZ;;;;;WAKA,WAAW,QAAQ;;WAEnB,UAAU;;;;;;WAMV,YAAY,cAAc;;;;;;;WAO1B,QAAQ,UAAU,kBAAkB;;;;;;;WAOpC,YAAY;;;cA6FjB,cAAW,SAAmB,KAAK,sCAAoC;;;;;;cAyBvE,QAAe,KAAG,SAAW,iBAAe,QAAQ,MAAM;;;;;;qBA4OnD"}