@runeditrun/rer 0.2.74 → 0.2.75

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/cli/export.mjs CHANGED
@@ -6,7 +6,7 @@ import { cliVersion } from './version.mjs';
6
6
 
7
7
  // Copy whole maintained source/tooling directories. Python publication scans
8
8
  // load sibling modules and data dynamically; they belong in the inventory too.
9
- export const sourceRoots = ['default-seed/public/rer-theme.css', 'default-seed/public/brand/mark.svg', 'default-seed/public/fonts/outfit', 'bin/rer.mjs', 'cli', 'modules/delivery-producer/declarations.mjs', 'modules/delivery-producer/bindings.mjs', 'modules/delivery-producer/migrations.mjs', 'modules/delivery-producer/mail.mjs', 'modules/job-queue', 'modules/release', 'modules/deploy-kit', 'modules/container', 'modules/demo-host', 'modules/demo', 'modules/integrations/core', 'modules/mail', 'modules/ai', 'modules/portability', 'modules/d1-transport', 'modules/erasure', 'modules/dependencies', 'modules/operator-auth', 'modules/owner-claim', 'operations', 'scripts/publish-check', 'scripts/publish-check.mjs', 'composition/git-source.mjs', 'edition-authoring/manifest.mjs', 'edition-authoring/files.mjs', 'foundation/runtime/seed-contract.mjs'];
9
+ export const sourceRoots = ['default-seed/public/rer-theme.css', 'default-seed/public/brand/mark.svg', 'default-seed/public/fonts/outfit', 'bin/rer.mjs', 'cli', 'modules/delivery-producer/declarations.mjs', 'modules/delivery-producer/bindings.mjs', 'modules/delivery-producer/migrations.mjs', 'modules/delivery-producer/mail.mjs', 'modules/job-queue', 'modules/release', 'modules/deploy-kit', 'modules/site', 'modules/container', 'modules/demo-host', 'modules/demo', 'modules/integrations/core', 'modules/mail', 'modules/ai', 'modules/portability', 'modules/d1-transport', 'modules/erasure', 'modules/dependencies', 'modules/operator-auth', 'modules/owner-claim', 'operations', 'scripts/publish-check', 'scripts/publish-check.mjs', 'composition/git-source.mjs', 'edition-authoring/manifest.mjs', 'edition-authoring/files.mjs', 'foundation/runtime/seed-contract.mjs'];
10
10
  export async function inventory(base, roots = sourceRoots) {
11
11
  const files = [];
12
12
  async function walk(path) {
@@ -6,6 +6,7 @@ import { privateDataScanner, decodedText } from './site-data.mjs';
6
6
  import { javascriptContent, javascriptContext } from './site-references.mjs';
7
7
  import { javascriptStrings } from './site-syntax.mjs';
8
8
  import { markupReferences, markupStrings, htmlElements, cssStrings } from './site-markup.mjs';
9
+ import { siteRuntime } from './site-runtime.mjs';
9
10
  import { refuse, RerError } from './errors.mjs';
10
11
  import { DEV_AI_MARKER, DEV_LAYER_MARKER } from './dev-identity.mjs';
11
12
 
@@ -66,7 +67,8 @@ export function servedFile(names, pathname) {
66
67
  * instance-only route, nothing fetched from another origin, no dev layer, and
67
68
  * none of the given private values (owner identity, secrets, the dev key).
68
69
  */
69
- export async function checkSite(folder, { privateValues = [], privateIdentities = [], root } = {}) {
70
+ export async function checkSite(folder, { privateValues = [], privateIdentities = [], root, runtime } = {}) {
71
+ const route = siteRuntime(runtime)?.endpoint;
70
72
  const all = await files(folder), names = new Set(all.keys());
71
73
  if (!names.has('index.html')) throw refuse('The run site has no index.html (its homepage).');
72
74
  if (!servedFile(names, '/run')) throw refuse('The run site has no /run page.');
@@ -112,7 +114,7 @@ export async function checkSite(folder, { privateValues = [], privateIdentities
112
114
  // fragment already fixes the instance path even when its tail is runtime.
113
115
  const boundary = !reference.dynamic || /[?#]/.test(url) || pathPrefix.endsWith('/');
114
116
  if (INSTANCE_ROUTES.some(route => (pathname === route && boundary) || pathname.startsWith(route + '/'))) problems.push(`${site} links to ${pathname}, which exists only on an installed instance`);
115
- else if (!reference.dynamic && !servedFile(names, safeDecode(pathname))) problems.push(`${site} links to ${pathname}, which the site does not have`);
117
+ else if (!reference.dynamic && !servedFile(names, safeDecode(pathname)) && pathname !== route) problems.push(`${site} links to ${pathname}, which the site does not have`);
116
118
  }
117
119
  }
118
120
  if (problems.length) throw refuse(`The run site has broken or out-of-site references: ${problems.slice(0, 8).join('; ')}${problems.length > 8 ? `; and ${problems.length - 8} more` : ''}.`);
@@ -0,0 +1,6 @@
1
+ // Credentialed child only of a real `rer deploy --site`. Its progress is
2
+ // captured by the command store, preserving the public CLI's JSON protocol.
3
+ import { buildSearchArtifacts } from '../modules/site/docs-search/artifacts.mjs';
4
+ const [corpus, assets, output, endpoint, compatibilityDate, domain] = process.argv.slice(2);
5
+ await buildSearchArtifacts({ corpus, assets, output, endpoint, compatibilityDate,
6
+ previousUrl: `https://${domain}/docs-search-vectors.json` }, { accountId: process.env.CLOUDFLARE_ACCOUNT_ID });
@@ -19,6 +19,7 @@ import { dirname, join, resolve, sep } from 'node:path';
19
19
  import { pathToFileURL } from 'node:url';
20
20
  import { buildClients, writeSiteAsset } from './site-client.mjs';
21
21
  import { htmlElements } from './site-markup.mjs';
22
+ import { searchCorpus } from './site-runtime.mjs';
22
23
  import { redactSiteOutput, siteBuildDiagnostic } from './site-diagnostics.mjs';
23
24
  import { ContractError, parseContract } from '../foundation/runtime/seed-contract.mjs';
24
25
 
@@ -64,7 +65,8 @@ try {
64
65
  await writeFile(join(server, 'package.json'), '{"type":"module"}\n');
65
66
  module = await import(pathToFileURL(join(server, chunk.fileName)).href);
66
67
  if (typeof module.sitePages !== 'function') fail(`${entry} must export sitePages(), returning { pages: [{ path, html }], assets: [public paths] }.`);
67
- const clientBuild = await buildClients(vite, root, output, clientJSON ? JSON.parse(clientJSON) : {}), clients = clientBuild.clients;
68
+ const options = clientJSON ? JSON.parse(clientJSON) : {};
69
+ const clientBuild = await buildClients(vite, root, output, options), clients = clientBuild.clients;
68
70
  styles = [...new Set([...styles,...clientBuild.styles])];
69
71
  const build = await module.sitePages({ styles, clients, ...(contract ? { contract } : {}) });
70
72
  if (!Array.isArray(build?.pages) || !Array.isArray(build.assets)) fail('sitePages() returns { pages, assets }.');
@@ -78,6 +80,10 @@ try {
78
80
  await mkdir(dirname(join(output, file)), { recursive: true });
79
81
  await writeFile(join(output, file), page.html);
80
82
  }
83
+ if (options.runtime) {
84
+ const pages = build.pages.map(page => ({...page, ids:new Set(htmlElements(page.html).map(element=>element.attributes.get('id')).filter(Boolean))}));
85
+ await writeFile(options.corpus, JSON.stringify(searchCorpus(pages, build.searchPages)));
86
+ }
81
87
  const publicDirectory = resolve(root, 'public');
82
88
  for (const asset of build.assets) {
83
89
  const source = typeof asset === 'string' && !asset.split('/').some(part => !part || part.startsWith('.')) && inside(publicDirectory, asset);
@@ -0,0 +1,55 @@
1
+ // The only executable site extension: Base's build-coupled docs search.
2
+ import { createHash } from 'node:crypto';
3
+ import { readFile } from 'node:fs/promises';
4
+ import { dirname, join } from 'node:path';
5
+ import { createRequire } from 'node:module';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { invalid } from './errors.mjs';
8
+ import { contained } from './project.mjs';
9
+ import { model, pooling, searchChunks } from '../modules/site/docs-search/index-build.mjs';
10
+
11
+ const digest = bytes => createHash('sha256').update(bytes).digest('hex');
12
+ export function siteRuntime(value) {
13
+ if (value === undefined) return;
14
+ if (!value || Object.keys(value).sort().join() !== 'bindings,corpus,endpoint,module,type' || value.type !== 'docs-search' || value.module !== 'docs-search'
15
+ || JSON.stringify(value.bindings) !== '["ASSETS","AI"]' || value.endpoint !== '/docs/search'
16
+ || !/^\.rer\/(?:[a-z0-9_-]+\/)+corpus\.json$/.test(value.corpus ?? '')) throw invalid('Run site runtime must declare { type: "docs-search", module: "docs-search", bindings: ["ASSETS", "AI"], endpoint: "/docs/search", corpus: ".rer/docs-search/corpus.json" }.');
17
+ return value;
18
+ }
19
+
20
+ /** Rendered sections must point to actual published pages and exact heading ids. */
21
+ export function searchCorpus(pages, searchPages) {
22
+ if (!Array.isArray(searchPages) || !searchPages.length) throw invalid('A docs-search sitePages() must return searchPages from the same render as its pages.');
23
+ const seen = new Set();
24
+ for (const page of searchPages) {
25
+ const published = pages.find(item => item.path === page?.href);
26
+ if (!published || !(page.href === '/docs' || page.href.startsWith('/docs/')) || !Array.isArray(page.searchSections) || seen.has(page.href)) throw invalid('Docs search corpus must name unique published docs pages.');
27
+ seen.add(page.href);
28
+ for (const section of page.searchSections) {
29
+ if (!section || typeof section.anchor !== 'string' || !section.anchor || !Array.isArray(section.titlePath) || !section.titlePath.length
30
+ || !section.titlePath.every(part => typeof part === 'string' && part.trim()) || typeof section.text !== 'string') throw invalid('Invalid docs search heading section.');
31
+ // Parse the rendered tree, not source Markdown or a second crawl.
32
+ if (!published.ids.has(section.anchor)) throw invalid('Docs search heading is absent from its rendered page.');
33
+ }
34
+ }
35
+ return searchPages;
36
+ }
37
+
38
+ export async function buildSiteRuntime(project, declaration, corpus, assets, { prepare = false, domain, compatibilityDate, store, signal } = {}) {
39
+ const pages = JSON.parse(await readFile(corpus, 'utf8'));
40
+ const chunks = searchChunks(pages), corpusHash = digest(chunks.map(chunk => chunk.hash).join('\n'));
41
+ if (prepare) {
42
+ const output = await contained(project.root, dirname(declaration.corpus), { optional: true });
43
+ await store.run('Preparing docs search', process.execPath, [fileURLToPath(new URL('./site-prepare.mjs', import.meta.url)), corpus, assets, output, declaration.endpoint, compatibilityDate, domain], {cwd:project.root, signal, heavy:false});
44
+ }
45
+ const { build } = createRequire(join(project.root, 'package.json'))('esbuild');
46
+ const worker = fileURLToPath(new URL('../modules/site/docs-search/worker.ts', import.meta.url));
47
+ const contract = { endpoint: declaration.endpoint, corpusHash, model, pooling };
48
+ const bundled = await build({ absWorkingDir: dirname(worker), stdin: { contents: `import {createSearchWorker} from ${JSON.stringify(worker)};export default createSearchWorker(${JSON.stringify(contract)});`,
49
+ resolveDir: dirname(worker), sourcefile: 'site-search-entry.ts', loader: 'ts' }, bundle: true, format: 'esm', platform: 'browser', target: 'es2022', write: false });
50
+ const source = bundled.outputFiles[0].text;
51
+ return { type: declaration.type, module: declaration.module, endpoint: declaration.endpoint, bindings: declaration.bindings, model, pooling, corpusHash, source };
52
+ }
53
+
54
+ export const runtimeSummary = runtime => runtime && ({ type: runtime.type, module: runtime.module, endpoint: runtime.endpoint, bindings: runtime.bindings,
55
+ model: runtime.model, pooling: runtime.pooling, corpusHash: runtime.corpusHash, moduleDigest: digest(runtime.source) });
package/cli/site.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { readFile, rename, rm, mkdir } from 'node:fs/promises';
1
+ import { cp, readFile, rename, rm, mkdir } from 'node:fs/promises';
2
2
  import { dirname, join, relative } from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
4
  import { contained } from './project.mjs';
@@ -9,10 +9,11 @@ import { shared } from './shared.mjs';
9
9
  import { unpublishedIdentities } from './site-private.mjs';
10
10
  import { privateSitePaths } from './site-inputs.mjs';
11
11
  import { redactSiteText } from './site-diagnostics.mjs';
12
+ import { siteRuntime, buildSiteRuntime, runtimeSummary } from './site-runtime.mjs';
12
13
 
13
14
  // The run site: a seed's static marketing pages, /run and docs, built from
14
15
  // edition identity with no installation data. A seed opts in with
15
- // commandAdapter's `site: { entry, output, declaration, config? }`: the module
16
+ // commandAdapter's `site: { entry, output, declaration, config?, runtime? }`: the module
16
17
  // whose sitePages({ styles }) returns the pages, the ignored folder the build
17
18
  // writes, the deploy declaration naming the run site's domain, and optionally
18
19
  // the Vite config holding the plugins the site pages need.
@@ -23,6 +24,8 @@ export function declaredSite(project) {
23
24
  if (!site) throw refuse('This checkout declares no run site. A seed opts in with site: { entry, output, declaration } in its command adapter; see SEED-COMMAND-CONTRACT.md.');
24
25
  if (!relativePath(site.entry) || !relativePath(site.output) || !relativePath(site.declaration) || (site.config !== undefined && !relativePath(site.config)) || (site.clientConfig !== undefined && !relativePath(site.clientConfig)) || ['src', 'public', 'node_modules', 'migrations'].some(top => site.output === top || site.output.startsWith(top + '/'))) throw invalid('The declared run site needs relative entries/configs, an output folder outside src, public and node_modules, and a deploy declaration.');
25
26
  if (site.clients !== undefined && (!site.clients || Array.isArray(site.clients) || typeof site.clients !== 'object' || Object.entries(site.clients).some(([name, entry]) => !/^[a-z][a-z0-9-]*$/i.test(name) || !relativePath(entry)))) throw invalid('Run site clients is a map of island names to relative client entry paths.');
27
+ const runtime = siteRuntime(site.runtime);
28
+ if (runtime && (runtime.corpus.startsWith(site.output + '/') || site.output.startsWith(runtime.corpus + '/'))) throw invalid('Search corpus must be outside the published site assets.');
26
29
  return site;
27
30
  }
28
31
 
@@ -46,19 +49,20 @@ async function privateValues(project) {
46
49
  }
47
50
 
48
51
  /** Render the run site into its declared folder, check it and replace the previous build. */
49
- export async function buildSite(project, store, signal) {
52
+ export async function buildSite(project, store, signal, { prepare = false, deployment } = {}) {
50
53
  const site = declaredSite(project);
51
54
  await contained(project.root, site.entry);
52
55
  if (site.config) await contained(project.root, site.config);
53
56
  if (site.clientConfig) await contained(project.root, site.clientConfig);
54
57
  for (const entry of Object.values(site.clients ?? {})) await contained(project.root, entry);
58
+ if (site.runtime) await contained(project.root, site.runtime.corpus, { optional: true });
55
59
  const folder = await contained(project.root, site.output, { optional: true });
56
60
  await mkdir(dirname(folder), { recursive: true });
57
61
  const staging = `${folder}.building-${process.pid}`;
58
62
  await rm(staging, { recursive: true, force: true });
59
63
  try {
60
64
  await mkdir(staging);
61
- try { await store.run('Building the run site', process.execPath, [fileURLToPath(new URL('./site-render.mjs', import.meta.url)), project.root, site.entry, staging, site.config ?? '', JSON.stringify({entries:site.clients ?? {}, config:site.clientConfig, privatePaths:privateSitePaths(project.adapter)})], { cwd: project.root, signal, heavy: false }); }
65
+ try { await store.run('Building the run site', process.execPath, [fileURLToPath(new URL('./site-render.mjs', import.meta.url)), project.root, site.entry, staging, site.config ?? '', JSON.stringify({entries:site.clients ?? {}, config:site.clientConfig, privatePaths:privateSitePaths(project.adapter), ...(site.runtime ? {runtime:site.runtime, corpus:`${staging}.corpus.json`} : {})})], { cwd: project.root, signal, heavy: false }); }
62
66
  catch (error) {
63
67
  const code = await readFile(`${staging}.refusal`, 'utf8').catch(() => '');
64
68
  if (code === 'site_private_input') throw new RerError(code, 'Run site client imports a private installation file or a file outside the seed and its declared dependencies.', 4);
@@ -69,25 +73,40 @@ export async function buildSite(project, store, signal) {
69
73
  if (diagnostic) throw commandFailure(redactSiteText(diagnostic.message), diagnostic);
70
74
  throw error;
71
75
  }
72
- const checked = await checkSite(staging, {root:project.root, ...await privateValues(project)});
76
+ const privacy = await privateValues(project);
77
+ const checkOptions = {root:project.root, ...privacy, ...(site.runtime ? {runtime:site.runtime} : {})};
78
+ let checked = await checkSite(staging, checkOptions);
79
+ let runtime;
80
+ if (site.runtime) {
81
+ try { runtime = await buildSiteRuntime(project, site.runtime, `${staging}.corpus.json`, staging, { prepare, domain:deployment?.domain, compatibilityDate:deployment?.compatibilityDate, store, signal }); }
82
+ catch (error) { if (error instanceof RerError) throw error; throw new RerError('site_search_failed', 'Docs search preparation failed; publication stopped. Check the previous artifact and Workers AI availability.', 1); }
83
+ if (prepare) checked = await checkSite(staging, checkOptions);
84
+ const corpus = await contained(project.root, site.runtime.corpus, {optional:true});
85
+ await mkdir(dirname(corpus), {recursive:true});
86
+ await cp(`${staging}.corpus.json`, corpus);
87
+ }
73
88
  await rm(folder, { recursive: true, force: true });
74
89
  await rename(staging, folder);
75
- return { folder, ...checked };
76
- } finally { await Promise.all([staging, `${staging}.render`, `${staging}.refusal`].map(path => rm(path, { recursive: true, force: true }))); }
90
+ return { folder, ...checked, ...(runtime ? {runtime} : {}) };
91
+ } finally { await Promise.all([staging, `${staging}.render`, `${staging}.refusal`, `${staging}.corpus.json`].map(path => rm(path, { recursive: true, force: true }))); }
77
92
  }
78
93
 
79
- async function siteDeployment(project, options, folder) {
94
+ async function siteDeployment(project, options, folder, runtime) {
80
95
  const site = declaredSite(project), environment = options.environment ?? 'production';
81
96
  const read = async path => { try { return JSON.parse(await readFile(await contained(project.root, path), 'utf8')); } catch (error) { if (error instanceof RerError) throw error; throw invalid(`Malformed ${path}.`); } };
82
97
  const app = await read(project.adapter.deploy?.declaration ?? 'deploy.json'), declaration = await read(site.declaration);
83
98
  const { sitePlan } = await import('../modules/deploy-kit/site.mjs');
84
- try { return sitePlan({ project: app.project, environment, compatibilityDate: app.compatibilityDate, declaration, assets: folder }); }
99
+ try { return sitePlan({ project: app.project, environment, compatibilityDate: app.compatibilityDate, declaration, assets: folder, runtime }); }
85
100
  catch (error) { throw invalid(`The run site deploy declaration is invalid (${error.message}). ${site.declaration} holds {"version": 1, "domain": "<apex hostname>"}.`); }
86
101
  }
87
102
 
88
103
  /** `rer build --site` and `rer deploy --site [--dry-run]`. */
89
104
  export async function siteCommand(project, options, store, signal, out) {
90
- const built = await buildSite(project, store, signal);
105
+ const prepare = options.verb !== 'build' && !options.dryRun;
106
+ if (prepare && declaredSite(project).runtime && ['CLOUDFLARE_ACCOUNT_ID', 'CLOUDFLARE_API_TOKEN'].some(name => !process.env[name]?.trim())) throw missing('CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN are required, with the run site token permissions in the deploy-kit README.');
107
+ const declaration = declaredSite(project);
108
+ const deployment = prepare && declaration.runtime ? await siteDeployment(project, options, '/') : undefined;
109
+ const built = await buildSite(project, store, signal, {prepare, deployment});
91
110
  if (!options.json && built.references.unresolved.length) {
92
111
  out.human(`Run site references: ${built.references.unresolved.length} runtime resource target(s) could not be resolved statically:`);
93
112
  for (const {asset, kind} of built.references.unresolved) out.human(` ${asset}: ${kind}`);
@@ -96,13 +115,23 @@ export async function siteCommand(project, options, store, signal, out) {
96
115
  // Output redaction masks an inherited PWD (a credential-shaped name), so the
97
116
  // checkout-relative folder is named too.
98
117
  const path = relative(project.root, built.folder);
99
- if (!options.json) out.human(`Run site written to ${path} (${built.pages} pages, ${built.files} files): ${built.folder}`);
100
- return { site: { folder: built.folder, path, pages: built.pages, files: built.files, references:built.references } };
118
+ if (!options.json) {
119
+ out.human(`Run site written to ${path} (${built.pages} pages, ${built.files} files): ${built.folder}`);
120
+ if (built.runtime) out.human(` runtime: docs-search; endpoint ${built.runtime.endpoint}; bindings ASSETS, AI; corpus ${built.runtime.corpusHash}; vectors prepared only on a real deploy`);
121
+ }
122
+ return { site: { folder: built.folder, path, pages: built.pages, files: built.files, references:built.references, ...(built.runtime ? {runtime:runtimeSummary(built.runtime)} : {}) } };
101
123
  }
102
- const plan = await siteDeployment(project, options, built.folder);
103
- const human = [`Run site plan: site Worker ${plan.worker}, Base-generated, its only binding the assets (the app's Worker ${plan.appWorker} is not touched)`, ` assets: ${plan.assets} (${built.files} files; HTML ${plan.assetsConfig.html_handling}, not found ${plan.assetsConfig.not_found_handling}; the Worker runs first)`,
124
+ const plan = await siteDeployment(project, options, built.folder, built.runtime);
125
+ const human = [`Run site plan: site Worker ${plan.worker}, Base-generated, ${built.runtime ? 'docs-search runtime with ASSETS and AI' : 'its only binding the assets'} (the app's Worker ${plan.appWorker} is not touched)`, ` assets: ${plan.assets} (${built.files} files; HTML ${plan.assetsConfig.html_handling}, not found ${plan.assetsConfig.not_found_handling}; the Worker runs first)`,
104
126
  ` custom domains: ${plan.hostnames.join(', ')}; workers.dev off`, ...plan.redirects.map(rule => ` redirect in the Worker: ${rule.from} -> ${rule.to} (${rule.status}, keeps ${rule.keeps.join(' and ')})`)];
105
- const summary = { worker: plan.worker, appWorker: plan.appWorker, module: plan.module, bindings: plan.bindings, assets: plan.assets, files: built.files, references:built.references, domain: plan.domain, hostnames: plan.hostnames, workersDev: false, runWorkerFirst: true, assetsConfig: plan.assetsConfig, redirects: plan.redirects.map(({ from, to, status }) => ({ from, to, status })) };
127
+ const { collectFiles } = await import('../modules/deploy-kit/artifact.mjs');
128
+ const { siteFingerprint } = await import('../modules/deploy-kit/site.mjs');
129
+ const files = await collectFiles(built.folder);
130
+ const runtime = runtimeSummary(built.runtime);
131
+ if (runtime) human.push(` runtime: ${runtime.type}; module ${runtime.module}; endpoint ${runtime.endpoint}; bindings ${runtime.bindings.join(', ')}; model ${runtime.model}; pooling ${runtime.pooling}; corpus ${runtime.corpusHash}`);
132
+ const fingerprint = siteFingerprint(plan, files, {preparing:Boolean(runtime) && !prepare});
133
+ if (runtime) human.push(` fingerprint: ${fingerprint}${prepare ? '' : ' (vectors prepared only on a real deploy)'}`);
134
+ const summary = { ...(runtime ? {runtime, fingerprint, vectors:prepare ? 'prepared' : 'prepare-on-deploy'} : {}), worker: plan.worker, appWorker: plan.appWorker, module: plan.module, bindings: plan.bindings, assets: plan.assets, files: built.files, references:built.references, domain: plan.domain, hostnames: plan.hostnames, workersDev: false, runWorkerFirst: true, assetsConfig: plan.assetsConfig, redirects: plan.redirects.map(({ from, to, status }) => ({ from, to, status })) };
106
135
  if (options.dryRun) {
107
136
  if (options.json) out.event('site', summary); else for (const line of human) out.human(line);
108
137
  store.report('deploy --site: dry run complete; no deployment occurred and no provider request was made.');
@@ -112,13 +141,12 @@ export async function siteCommand(project, options, store, signal, out) {
112
141
  if (names.some(name => !process.env[name]?.trim())) throw missing('CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN are required, with the run site token permissions in the deploy-kit README.');
113
142
  if (!options.json) for (const line of human) out.human(line);
114
143
  const { cloudflare } = await import('../modules/deploy-kit/provider.mjs');
115
- const { collectFiles } = await import('../modules/deploy-kit/artifact.mjs');
116
144
  const { siteDeploy, siteReadbackSummary } = await import('../modules/deploy-kit/site.mjs');
117
145
  const environment = options.environment ?? 'production';
118
146
  try {
119
147
  const api = cloudflare({ accountId: process.env.CLOUDFLARE_ACCOUNT_ID, token: process.env.CLOUDFLARE_API_TOKEN });
120
148
  // The receipt is for the person; ownership is read from the provider, so a fresh checkout deploys too.
121
- const result = await siteDeploy({ api, plan, files: await collectFiles(built.folder), receiptPath: join(project.root, '.rer', 'deploy', `site-${environment}.json`) });
149
+ const result = await siteDeploy({ api, plan, files, receiptPath: join(project.root, '.rer', 'deploy', `site-${environment}.json`) });
122
150
  return { dryRun: false, deployed: true, origin: result.origin, site: summary };
123
151
  } catch (error) {
124
152
  if (error instanceof RerError) throw error;
@@ -1,5 +1,10 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.75
4
+
5
+ - **Custom-origin owner claims use the recorded app origin (#374).** Native deployment inspection retains the configured public origin from the deployment receipt, so owner claim and status work for custom domains while the ownership guard still refuses a claim at a different origin. Existing workers.dev deployments keep their derived origin.
6
+ - **Run sites can opt into build-coupled docs search (#375).** Site builds prepare the search corpus and runtime, deploys reuse published vectors or generate them through Workers AI, and readback verifies the serving runtime with its exact AI/assets bindings. Search results link to document headings and provider failures refuse publication.
7
+
3
8
  ## 0.2.74
4
9
 
5
10
  - **Restores replay more later migrations (#359).** Archive admission and replay accept row-less targets and row-less tables (restored in the destination's definition), RAISE-only guard triggers, statements that read views, and row-preserving CHECK rebuilds, so retained archives from before those migrations restore exactly (Vector: 121 tables / 23 rows; Penny with its settings and clock replayed).
@@ -181,23 +181,68 @@ A seed's run site (`run-<seed>.com`: its marketing homepage, `/run` and docs, wr
181
181
  The domain is an apex hostname: no scheme, path, port, upper case or `www.`. The plan (`sitePlan`) names:
182
182
 
183
183
  - the Worker `<project>-<environment>--site`. Owner Worker names never contain `--`, so it can never be the installed app's Worker (`<project>-<environment>`), and a site deploy never reads or writes the app Worker or any of its resources;
184
- - its one module, `site-worker.mjs` (`SITE_WORKER`): fixed content Base generates, with no seed code. Its only binding is the assets (`ASSETS`), it runs first on every request (`run_worker_first`), and it has no secrets, no schedules and workers.dev off. A request to `www.<domain>` gets a 301 to `https://<domain>` with path and query kept; every other request is answered from the assets exactly as an assets-only Worker would answer it: the `rer build --site` folder with `html_handling: auto-trailing-slash` (`/run` serves `run.html`) and `not_found_handling: 404-page`;
184
+ - by default its one module, `site-worker.mjs` (`SITE_WORKER`): fixed content Base generates, with no seed code. Its only binding is the assets (`ASSETS`), it runs first on every request (`run_worker_first`), and it has no secrets, no schedules and workers.dev off. A request to `www.<domain>` gets a 301 to `https://<domain>` with path and query kept; every other request is answered from the assets exactly as an assets-only Worker would answer it: the `rer build --site` folder with `html_handling: auto-trailing-slash` (`/run` serves `run.html`) and `not_found_handling: 404-page`;
185
185
  - the apex as a Workers Custom Domain, and `www.<domain>` as a second Custom Domain on the same Worker, so the www host has DNS and a certificate and its requests reach the Worker's redirect.
186
186
 
187
187
  No zone ruleset is read or written. Every request now invokes the Worker: one page view costs one Worker request for the page and one per same-origin file it loads (the default seed's run site: at most 7 per uncached page view).
188
188
 
189
- `rer deploy --site --dry-run` builds the site and prints that plan (`--json`: a `site` event and a result with `dryRun: true`, `deployed: false` and the same `site` object) with no provider request and nothing written, even with `CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_API_TOKEN` set. Without `--dry-run` it needs both inputs. Ownership is read from the provider alone, so a deploy from a fresh checkout (a CI runner with no `.rer/`) recognises the site it deployed before:
189
+ `rer deploy --site --dry-run` builds the site and prints that plan (`--json`: a `site` event and a result with `dryRun: true`, `deployed: false` and the same `site` object) with local build outputs but no provider request or remote write, even with `CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_API_TOKEN` set. Without `--dry-run` it needs both inputs. Ownership is read from the provider alone, so a deploy from a fresh checkout (a CI runner with no `.rer/`) recognises the site it deployed before:
190
190
 
191
191
  - the Worker is the kit's when its latest deployment serves, at 100%, the Worker's newest version, and that version's message annotation is the kit's `rer-site:<fingerprint>` (every site upload sets it);
192
192
  - a Custom Domain is the kit's when its service is the kit's Worker.
193
193
 
194
194
  A read-only preflight reads the zone (it must be in this account, else `site-zone-missing`), the Worker and the zone's Custom Domains, and refuses before any write: `resource-name-collision` for a Worker of the name whose live version the kit did not upload, or for a hostname attached to another service (or to a Worker that is not the kit's); `owned-resource-replaced` for a kit Worker whose latest deployment is not the kit's upload (a dashboard rollback or a split deployment). It then uploads the assets and the site Worker, checks that the new version is live, turns workers.dev off, attaches each missing hostname, and reads the Worker and both domains back. Both post-upload Worker checks share a 90-second upload window: missing visibility or the exact preflight version waits with backoff until the upload response's version serves alone as newest with its expected fingerprint. A foreign version, changed fingerprint or split deployment refuses immediately. A timeout names the last serving/newest versions and fingerprint. A repeat attaches nothing new. `.rer/deploy/site-<environment>.json` receives a receipt for the person; it is never read. Provider propagation cases are tested against the fake Cloudflare API in `tests/site-provider.mjs`, where every zone ruleset path answers 403.
195
195
 
196
+ A seed can opt into docs search through its command adapter's `site.runtime`:
197
+
198
+ ```ts
199
+ runtime: {
200
+ type: 'docs-search', module: 'docs-search', bindings: ['ASSETS', 'AI'],
201
+ endpoint: '/docs/search', corpus: '.rer/docs-search/corpus.json',
202
+ }
203
+ ```
204
+
205
+ This selects Base's docs-search implementation rather than seed JavaScript.
206
+ The site Worker adds the query endpoint and the Workers AI binding; its asset
207
+ handling, www redirect, ownership checks and Custom Domains stay the same.
208
+ No application binding, seed-defined ownership annotation or separate Wrangler
209
+ configuration/deployment is accepted. The domain declaration is unchanged.
210
+ Without `site.runtime`, the assets-only path is unchanged.
211
+
212
+ The renderer produces `pages`, `assets` and
213
+ `searchPages: [{ href, searchSections: [{ anchor, titlePath, text }] }]` from one
214
+ `sitePages` call and writes the latter to the declared staging corpus. Build and
215
+ dry run make no provider or embedding requests. Their plan reports runtime type,
216
+ module, bindings, endpoint, model, pooling, `corpusHash`, module digest and the
217
+ deployment fingerprint; it does not claim vectors exist.
218
+
219
+ Only real deployment prepares vectors. It uses the corpus parent as its local
220
+ preparation/cache directory and always reads the previous published index from
221
+ `https://<site domain>/docs-search-vectors.json`. Model
222
+ `@cf/baai/bge-base-en-v1.5`, pooling `cls` and 768 dimensions are fixed by the
223
+ Base module. Vectors are reused by model, pooling and chunk hash with valid
224
+ matching dimensions. A previous-index 404 permits a first index; other fetch,
225
+ parse or embedding errors stop before any site publication. The same render's
226
+ assets, completed vector index and query module are then uploaded together in
227
+ one site deployment. There is no second render or separate search deployment.
228
+
229
+ The UI source is copied from `modules/site/docs-search` under the seed's chosen
230
+ source path, with `site.clients.docsSearch` naming its `client.ts`. The seed
231
+ renders `SearchField`, imports `search.css`, loads the emitted island module and
232
+ provides `--ink`, `--ink-soft`, `--rule` and `--paper`. The rendered page layout
233
+ and copy stay seed-owned. Local builds have no prepared semantic search service.
234
+
235
+ For CI, the `run-site` environment supplies `CLOUDFLARE_ACCOUNT_ID` from
236
+ `vars.CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_API_TOKEN` from
237
+ `secrets.CLOUDFLARE_API_TOKEN`. After a frozen install, run the checkout's pinned
238
+ `pnpm exec rer deploy --site`. The guarded template is `export/run-site.yml`.
239
+
196
240
  The token needs, beyond the owner-account permissions above:
197
241
 
198
242
  | Permission | Scope | Used for |
199
243
  | --- | --- | --- |
200
244
  | Workers Scripts: Edit | the account | the site Worker upload, its assets, versions and deployments, workers.dev, and Workers Custom Domains (`/workers/domains`) |
245
+ | Workers AI: Read/Edit | the account, docs-search sites only | preparing embeddings and the runtime AI binding |
201
246
  | Zone: Read | the run site zones | finding the zone by name |
202
247
  | Workers Routes: Edit | the run site zones | Workers Custom Domains, which also create their DNS records and certificates |
203
248
 
@@ -102,7 +102,8 @@ export async function main(argv = process.argv.slice(2), env = process.env, {fet
102
102
  assert(live && sameDeployment(live, state.receipt.provider), 'owned-resource-replaced');
103
103
  const rows = await api.request(`/workers/scripts/${target.worker}/secrets`);
104
104
  assert(Array.isArray(rows), 'invalid-secret-list');
105
- return {ok:true, origin:target.origin, versionId:live.versionId, retiredSecrets, ownerClaim:state.ownerClaim, liveSecrets:rows.map(row => row.name)};
105
+ // Native uploaders record their configured app origin with the deployment identity.
106
+ return {ok:true, origin:state.receipt.origin ?? target.origin, versionId:live.versionId, retiredSecrets, ownerClaim:state.ownerClaim, liveSecrets:rows.map(row => row.name)};
106
107
  }
107
108
  const current = retiredSecrets.length && Array.isArray(declaration.secrets) ? {...declaration,secrets:declaration.secrets.filter(item => !retiredSecrets.includes(item?.binding))} : declaration;
108
109
  artifact ??= await ownerArtifact(root,values.product);
@@ -1,6 +1,7 @@
1
1
  import { workerSettings } from './owner.mjs';
2
2
  import { readinessAPI } from './readiness-window.mjs';
3
3
  import { assert } from './validation.mjs';
4
+ import { verifySiteRuntime } from './site-runtime.mjs';
4
5
 
5
6
  const ANNOTATION = /^rer-site:[0-9a-f]{64}$/;
6
7
  function refuse(code, worker) { return Object.assign(new Error(code), { resource: `worker:${worker}` }); }
@@ -33,7 +34,7 @@ export async function ownedSiteVersion(api, worker) {
33
34
 
34
35
  /** Only the upload response and the exact preflight version may appear while
35
36
  * Cloudflare's deployment and version reads converge. Never replay the upload. */
36
- export async function waitForSiteUpload({ api, worker, versionId, fingerprint, previous, window }) {
37
+ export async function waitForSiteUpload({ api, worker, versionId, fingerprint, previous, window, runtime, module }) {
37
38
  const bounded = readinessAPI(api, window, 'site-upload-timeout');
38
39
  const annotation = `rer-site:${fingerprint}`;
39
40
  let lastSeen = null, delay = 2000;
@@ -48,7 +49,16 @@ export async function waitForSiteUpload({ api, worker, versionId, fingerprint, p
48
49
  || lastSeen.visible && lastSeen.annotation !== expected
49
50
  || lastSeen.versionId === previous?.versionId && lastSeen.deploymentId !== previous.deploymentId)
50
51
  throw refuse('owned-resource-replaced', worker);
51
- if (lastSeen.current && lastSeen.versionId === versionId && lastSeen.annotation === annotation) return lastSeen;
52
+ if (lastSeen.current && lastSeen.versionId === versionId && lastSeen.annotation === annotation) {
53
+ if (!runtime) return lastSeen;
54
+ try {
55
+ await verifySiteRuntime(bounded, worker, versionId, runtime, module);
56
+ return lastSeen;
57
+ } catch (error) {
58
+ if (window.remaining() <= 0 || error.name === 'TimeoutError') throw timeout(error);
59
+ if (error.status !== 404) throw error;
60
+ }
61
+ }
52
62
  }
53
63
  await window.sleep(Math.min(delay, window.remaining()));
54
64
  delay = Math.min(delay * 2, 10000);
@@ -0,0 +1,33 @@
1
+ import { assert, hash } from './validation.mjs';
2
+
3
+ /** Only the immutable Base docs-search bundle may extend the site Worker. */
4
+ export function siteRuntime(runtime) {
5
+ if (runtime === undefined) return undefined;
6
+ assert(runtime && typeof runtime === 'object' && !Array.isArray(runtime)
7
+ && Object.keys(runtime).sort().join() === 'bindings,corpusHash,endpoint,model,module,pooling,source,type'
8
+ && runtime.type === 'docs-search' && runtime.module === 'docs-search' && runtime.endpoint === '/docs/search'
9
+ && Array.isArray(runtime.bindings) && runtime.bindings.join() === 'ASSETS,AI'
10
+ && typeof runtime.model === 'string' && runtime.model.trim().length > 0 && runtime.pooling === 'cls'
11
+ && typeof runtime.corpusHash === 'string' && /^[a-f0-9]{64}$/.test(runtime.corpusHash)
12
+ && typeof runtime.source === 'string' && runtime.source.length > 0, 'invalid-site-runtime');
13
+ return { ...runtime, bindings: ['ASSETS', 'AI'] };
14
+ }
15
+
16
+ export const siteRuntimeBindings = runtime => [{ type: 'assets', name: 'ASSETS' }, ...(runtime ? [{ type: 'ai', name: 'AI' }] : [])];
17
+
18
+ /** Read the exact version, never Worker-scoped settings or seed annotations.
19
+ * Source equality proves the embedded corpus/model/pooling contract, including
20
+ * its executable implementation, rather than trusting a claimed source digest. */
21
+ export async function verifySiteRuntime(api, worker, versionId, runtime, module) {
22
+ const replaced = () => Object.assign(new Error('owned-resource-replaced'), { resource: `worker:${worker}` });
23
+ const version = await api.request(`/workers/scripts/${worker}/versions/${versionId}`);
24
+ const bindings = version?.resources?.bindings;
25
+ const expected = siteRuntimeBindings(runtime);
26
+ if (version?.id !== versionId || !Array.isArray(bindings) || bindings.length !== expected.length
27
+ || expected.some(binding => bindings.filter(row => row?.name === binding.name && row.type === binding.type).length !== 1)) throw replaced();
28
+ const content = await api.workerContent(worker, versionId);
29
+ const parts = [...content.parts];
30
+ if (content.entry !== module || parts.length !== 1 || parts[0][0] !== module
31
+ || typeof parts[0][1]?.arrayBuffer !== 'function'
32
+ || hash(Buffer.from(await parts[0][1].arrayBuffer())) !== hash(runtime.source)) throw replaced();
33
+ }
@@ -6,11 +6,13 @@ import { uploadAssets, workerOrigin } from './worker.mjs';
6
6
  import { readinessWindow, readinessAPI } from './readiness-window.mjs';
7
7
  import { uploadVersionId } from './uploaded-worker.mjs';
8
8
  import { ownedSiteVersion, waitForSiteDomains, waitForSiteUpload } from './site-readback.mjs';
9
+ import { siteRuntime, siteRuntimeBindings } from './site-runtime.mjs';
9
10
  export { servedVersion, siteReadbackSummary } from './site-readback.mjs';
10
11
 
11
12
  /* A seed's run site (run-<seed>.com): the folder `rer build --site` writes,
12
- * served on the owner's own account by a Base-generated module Worker (fixed
13
- * content, no seed code) whose only binding is its assets. The Worker runs
13
+ * served on the owner's own account by a Base-generated module Worker (no
14
+ * seed code). Its default binding is its assets; opt-in docs search adds AI
15
+ * and an immutable Base-generated search bundle. The Worker runs
14
16
  * first on every request: www.<domain> gets a 301 to the apex with path and
15
17
  * query kept, and everything else is answered from the assets. It has no
16
18
  * secrets and no schedules, workers.dev stays off, and its name can never be
@@ -58,16 +60,32 @@ export function siteWorkerName(project, environment) {
58
60
  }
59
61
 
60
62
  /** Everything a site deploy will do, with no provider request. */
61
- export function sitePlan({ project, environment, compatibilityDate, declaration, assets }) {
63
+ export function sitePlan({ project, environment, compatibilityDate, declaration, assets, runtime }) {
62
64
  const { domain } = siteDeclaration(declaration);
63
65
  assert(/^\d{4}-\d{2}-\d{2}$/.test(compatibilityDate ?? ''), 'invalid-plan');
64
66
  assert(typeof assets === 'string' && assets.startsWith('/'), 'invalid-site-assets');
67
+ runtime = siteRuntime(runtime);
65
68
  return { version: 1, worker: siteWorkerName(project, environment), appWorker: ownerWorkerName(project, environment), module: SITE_MODULE, assets, compatibilityDate,
66
- bindings: ['ASSETS'], secrets: [], crons: [], workersDev: false, runWorkerFirst: true, assetsConfig: { ...SITE_ASSETS_CONFIG },
69
+ bindings: runtime ? [...runtime.bindings] : ['ASSETS'], secrets: [], crons: [], workersDev: false, runWorkerFirst: true, assetsConfig: { ...SITE_ASSETS_CONFIG },
70
+ ...(runtime ? { runtime } : {}),
67
71
  domain, hostnames: [domain, `www.${domain}`],
68
72
  redirects: [{ from: `https://www.${domain}/*`, to: `https://${domain}/`, status: 301, keeps: ['path', 'query'] }] };
69
73
  }
70
74
 
75
+ /** Assets-only plans retain the original fingerprint byte for byte. */
76
+ export function siteFingerprint(plan, files, { preparing = false } = {}) {
77
+ const runtime = siteRuntime(plan.runtime);
78
+ const identity = { files: files.map(({ path, sha256 }) => ({ path, sha256 })), config: plan.assetsConfig,
79
+ module: hash(runtime?.source ?? SITE_WORKER), compatibilityDate: plan.compatibilityDate };
80
+ if (runtime) {
81
+ const vectors = files.find(file => file.path === 'docs-search-vectors.json');
82
+ assert(preparing || vectors && /^[a-f0-9]{64}$/.test(vectors.sha256), 'missing-site-search-vectors');
83
+ identity.runtime = { type: runtime.type, module: runtime.module, endpoint: runtime.endpoint, bindings: runtime.bindings,
84
+ model: runtime.model, pooling: runtime.pooling, corpusHash: runtime.corpusHash, vectors: preparing ? 'prepare-on-deploy' : vectors.sha256 };
85
+ }
86
+ return hash(identity);
87
+ }
88
+
71
89
  async function writeReceipt(path, receipt) {
72
90
  await mkdir(dirname(path), { recursive: true, mode: 0o700 });
73
91
  const temporary = `${path}.${process.pid}.tmp`;
@@ -79,6 +97,8 @@ async function writeReceipt(path, receipt) {
79
97
  export async function siteDeploy({ api, plan, files, receiptPath, readiness = {} }) {
80
98
  assert(typeof receiptPath === 'string' && receiptPath.length, 'missing-receipt-path');
81
99
  assert(plan?.module === SITE_MODULE && Array.isArray(files) && files.some(file => file.path === 'index.html'), 'invalid-site-assets');
100
+ const runtime = siteRuntime(plan.runtime);
101
+ const fingerprint = siteFingerprint(plan, files);
82
102
  const zones = await api.zoneRequest(`/zones?name=${plan.domain}&account.id=${api.accountId}`);
83
103
  const zone = Array.isArray(zones) ? zones.find(row => row?.name === plan.domain && row.account?.id === api.accountId) : null;
84
104
  if (!zone) throw refuse('site-zone-missing', 'zone', plan.domain);
@@ -91,19 +111,18 @@ export async function siteDeploy({ api, plan, files, receiptPath, readiness = {}
91
111
  if (row && (!previous || row.service !== plan.worker)) throw refuse('resource-name-collision', 'domain', hostname);
92
112
  }
93
113
 
94
- const fingerprint = hash({ files: files.map(({ path, sha256 }) => ({ path, sha256 })), config: plan.assetsConfig, module: hash(SITE_WORKER), compatibilityDate: plan.compatibilityDate });
95
114
  const jwt = await uploadAssets(api, plan.worker, files);
96
115
  const body = new FormData();
97
- body.set('metadata', new Blob([JSON.stringify({ main_module: SITE_MODULE, compatibility_date: plan.compatibilityDate, bindings: [{ type: 'assets', name: 'ASSETS' }],
116
+ body.set('metadata', new Blob([JSON.stringify({ main_module: SITE_MODULE, compatibility_date: plan.compatibilityDate, bindings: siteRuntimeBindings(runtime),
98
117
  assets: { jwt, config: { ...plan.assetsConfig, run_worker_first: true } }, annotations: { 'workers/message': `rer-site:${fingerprint}` } })], { type: 'application/json' }));
99
- body.set(SITE_MODULE, new Blob([SITE_WORKER], { type: 'application/javascript+module' }), SITE_MODULE);
118
+ body.set(SITE_MODULE, new Blob([runtime?.source ?? SITE_WORKER], { type: 'application/javascript+module' }), SITE_MODULE);
100
119
  const window = readiness.window ?? readinessWindow(readiness);
101
120
  window.start();
102
121
  api = readinessAPI(api, window, 'site-upload-timeout');
103
122
  const upload = await api.request(`/workers/scripts/${plan.worker}`, { method: 'PUT', body });
104
123
  const versionId = uploadVersionId(upload);
105
124
  assert(versionId, 'invalid-upload-version');
106
- const readback = () => waitForSiteUpload({ api, worker: plan.worker, versionId, fingerprint, previous, window });
125
+ const readback = () => waitForSiteUpload({ api, worker: plan.worker, versionId, fingerprint, previous, window, runtime, module: SITE_MODULE });
107
126
  await readback();
108
127
  await workerOrigin(api, plan.worker, { enable: true, workersDev: false });
109
128
  for (const hostname of plan.hostnames) {
@@ -0,0 +1,18 @@
1
+ import './search.css';
2
+
3
+ /** Static markup; the standalone site's client enhances each instance. */
4
+ export function SearchField({ id, endpoint = '/docs/search' }: { id: string; endpoint?: string }) {
5
+ return <div className="docs-search" data-docs-search data-endpoint={endpoint}>
6
+ <label className="docs-search-label" htmlFor={id}>Search docs</label>
7
+ <div className="docs-search-field">
8
+ <input id={id} type="search" placeholder="Search docs" autoComplete="off" spellCheck={false}
9
+ role="combobox" aria-autocomplete="list" aria-haspopup="listbox" aria-expanded="false"
10
+ aria-controls={`${id}-results`} aria-describedby={`${id}-status`} />
11
+ <kbd aria-hidden="true">/</kbd>
12
+ </div>
13
+ <div className="docs-search-panel" data-search-panel hidden>
14
+ <p id={`${id}-status`} className="docs-search-status" role="status" aria-live="polite" aria-atomic="true">Search the docs</p>
15
+ <ul id={`${id}-results`} className="docs-search-results" role="listbox" aria-label="Search results" hidden />
16
+ </div>
17
+ </div>;
18
+ }
@@ -0,0 +1,54 @@
1
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
2
+ import { relative, resolve } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { createRequire } from 'node:module';
5
+ import { buildSearchIndex } from './index-build.mjs';
6
+
7
+ // The seed owns its build toolchain; rer remains dependency-free for offline launch.
8
+ const { build } = createRequire(resolve('package.json'))('esbuild');
9
+
10
+ /** Explicit credentialed build step. A failure stops publication; no lexical fallback. */
11
+ export async function buildSearchArtifacts({ corpus, assets, output, previousUrl, endpoint = '/docs/search', localName = 'docs-search-local', compatibilityDate = '2026-09-08' }, { embed, accountId } = {}) {
12
+ const pages = JSON.parse(await readFile(corpus, 'utf8'));
13
+ await mkdir(output, { recursive: true });
14
+ const indexPath = resolve(output, 'index.json');
15
+ const previous = [];
16
+ try { previous.push(JSON.parse(await readFile(indexPath, 'utf8'))); }
17
+ catch (error) { if (error.code !== 'ENOENT') throw error; }
18
+ if (previousUrl) {
19
+ const response = await fetch(previousUrl, { signal: AbortSignal.timeout(15000) });
20
+ if (response.status !== 404) {
21
+ if (!response.ok) throw Error(`Previous search artifact unavailable (${response.status}); build stopped.`);
22
+ previous.push(await response.json());
23
+ }
24
+ }
25
+ const remoteEmbed = async (model, input) => {
26
+ if (!process.env.CLOUDFLARE_API_TOKEN || !accountId) throw Error('Search indexing requires CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN (Workers AI Read).');
27
+ const response = await fetch(`https://api.cloudflare.com/client/v4/accounts/${accountId}/ai/run/${model}`, {
28
+ method: 'POST', headers: { Authorization: `Bearer ${process.env.CLOUDFLARE_API_TOKEN}`, 'Content-Type': 'application/json' },
29
+ body: JSON.stringify(input), signal: AbortSignal.timeout(60000),
30
+ });
31
+ if (!response.ok) throw Error(`Workers AI embedding failed (${response.status}); build stopped.`);
32
+ const body = await response.json();
33
+ if (!body.success) throw Error('Workers AI refused embeddings; build stopped.');
34
+ return body.result;
35
+ };
36
+ const { index, counts } = await buildSearchIndex(pages, { previous, embed: embed ?? remoteEmbed,
37
+ onBatch: ({ embedded, total }) => console.log(`Docs search embeddings: ${embedded}/${total}`) });
38
+ const bytes = JSON.stringify(index);
39
+ await writeFile(`${indexPath}.new`, bytes);
40
+ await rename(`${indexPath}.new`, indexPath);
41
+ // Published with the same assets as the pages; the next clean deployment
42
+ // reuses these vectors by content hash, never a crawler or an update timer.
43
+ await writeFile(resolve(assets, 'docs-search-vectors.json'), bytes);
44
+ const runtime = fileURLToPath(new URL('./worker.ts', import.meta.url));
45
+ await build({ stdin: { contents: `import {createSearchWorker} from ${JSON.stringify(runtime)};export default createSearchWorker(${JSON.stringify({ endpoint, corpusHash: index.corpusHash })});`,
46
+ resolveDir: resolve(output), sourcefile: 'site-search-entry.ts', loader: 'ts' }, bundle: true, format: 'esm', platform: 'browser', target: 'es2022', outfile: resolve(output, 'worker.mjs') });
47
+ const configuration = { name: localName, main: './worker.mjs', compatibility_date: compatibilityDate,
48
+ ...(accountId ? { account_id: accountId } : {}), workers_dev: false,
49
+ assets: { directory: relative(resolve(output), resolve(assets)), binding: 'ASSETS', run_worker_first: true, html_handling: 'auto-trailing-slash', not_found_handling: '404-page' },
50
+ ai: { binding: 'AI', remote: true } };
51
+ await writeFile(resolve(output, 'wrangler.json'), `${JSON.stringify(configuration, null, 2)}\n`);
52
+ console.log(`Docs search: total=${counts.total} reused=${counts.reused} embedded=${counts.embedded} bytes=${Buffer.byteLength(bytes)}`);
53
+ return { index, counts };
54
+ }
@@ -0,0 +1,194 @@
1
+ type SearchResult = { href: string; titlePath: string[]; snippet: string; score: number };
2
+ const mounted = new WeakMap<HTMLElement, () => void>();
3
+
4
+ function readResults(payload: unknown): SearchResult[] {
5
+ if (!payload || typeof payload !== 'object' || !('results' in payload) || !Array.isArray(payload.results)) {
6
+ throw new Error('Invalid search response');
7
+ }
8
+ return payload.results.slice(0, 5).map((value: unknown) => {
9
+ if (!value || typeof value !== 'object' || !('href' in value) || typeof value.href !== 'string'
10
+ || !('titlePath' in value) || !Array.isArray(value.titlePath) || !value.titlePath.every((part: unknown) => typeof part === 'string')
11
+ || !('snippet' in value) || typeof value.snippet !== 'string'
12
+ || !('score' in value) || typeof value.score !== 'number' || !Number.isFinite(value.score)) {
13
+ throw new Error('Invalid search result');
14
+ }
15
+ const url = new URL(value.href, document.baseURI);
16
+ if (url.origin !== location.origin || !['http:', 'https:'].includes(url.protocol)) throw new Error('Invalid search link');
17
+ return { href: url.href, titlePath: value.titlePath, snippet: value.snippet, score: value.score };
18
+ });
19
+ }
20
+
21
+ function mount(root: HTMLElement): () => void {
22
+ const input = root.querySelector<HTMLInputElement>('input[type="search"]');
23
+ const panel = root.querySelector<HTMLElement>('[data-search-panel]');
24
+ const list = root.querySelector<HTMLUListElement>('[role="listbox"]');
25
+ const status = root.querySelector<HTMLElement>('[role="status"]');
26
+ if (!input || !panel || !list || !status) throw new Error('Incomplete docs search field');
27
+ const address = root.dataset.endpoint;
28
+ if (!address) throw new Error('Docs search endpoint is missing');
29
+ const baseEndpoint = new URL(address, document.baseURI);
30
+ const listeners = new AbortController();
31
+ let request: AbortController | undefined;
32
+ let timer: ReturnType<typeof setTimeout> | undefined;
33
+ let revision = 0;
34
+ let links: HTMLAnchorElement[] = [];
35
+ let active = -1;
36
+ let renderedQuery: string | undefined;
37
+
38
+ function cancel() {
39
+ revision += 1;
40
+ clearTimeout(timer);
41
+ timer = undefined;
42
+ request?.abort();
43
+ request = undefined;
44
+ list!.removeAttribute('aria-busy');
45
+ }
46
+ function select(index: number) {
47
+ active = index;
48
+ links.forEach((link, position) => link.setAttribute('aria-selected', String(position === active)));
49
+ if (links[active]) input!.setAttribute('aria-activedescendant', links[active].id);
50
+ else input!.removeAttribute('aria-activedescendant');
51
+ }
52
+ function close() {
53
+ cancel();
54
+ panel!.hidden = true;
55
+ input!.setAttribute('aria-expanded', 'false');
56
+ select(-1);
57
+ }
58
+ function message(text: string) {
59
+ links = [];
60
+ select(-1);
61
+ list!.replaceChildren();
62
+ list!.hidden = true;
63
+ status!.textContent = text;
64
+ }
65
+ function show() {
66
+ panel!.hidden = false;
67
+ input!.setAttribute('aria-expanded', 'true');
68
+ }
69
+ function render(results: SearchResult[]) {
70
+ message(results.length ? '' : 'No results');
71
+ const fragment = document.createDocumentFragment();
72
+ links = results.map((result, index) => {
73
+ const item = document.createElement('li');
74
+ item.setAttribute('role', 'none');
75
+ const link = document.createElement('a');
76
+ link.id = `${list!.id}-${index}`;
77
+ link.href = result.href;
78
+ link.tabIndex = -1;
79
+ link.setAttribute('role', 'option');
80
+ link.setAttribute('aria-selected', 'false');
81
+ const title = document.createElement('span');
82
+ title.className = 'docs-search-result-title';
83
+ title.textContent = result.titlePath.join(' > ');
84
+ const snippet = document.createElement('span');
85
+ snippet.className = 'docs-search-result-snippet';
86
+ snippet.textContent = result.snippet;
87
+ link.appendChild(title);
88
+ link.appendChild(snippet);
89
+ item.appendChild(link);
90
+ fragment.appendChild(item);
91
+ return link;
92
+ });
93
+ list!.appendChild(fragment);
94
+ list!.hidden = !links.length;
95
+ }
96
+ function search() {
97
+ cancel();
98
+ show();
99
+ renderedQuery = undefined;
100
+ const query = input!.value.trim();
101
+ if (query.length < 2) { message('Search the docs'); return; }
102
+ message('Searching…');
103
+ const current = revision;
104
+ timer = setTimeout(async () => {
105
+ const controller = new AbortController();
106
+ request = controller;
107
+ list!.setAttribute('aria-busy', 'true');
108
+ try {
109
+ const endpoint = new URL(baseEndpoint);
110
+ endpoint.searchParams.set('q', query);
111
+ const response = await fetch(endpoint, { signal: controller.signal, headers: { Accept: 'application/json' } });
112
+ if (!response.ok) throw new Error('Search request failed');
113
+ const results = readResults(await response.json());
114
+ if (current !== revision || controller.signal.aborted) return;
115
+ renderedQuery = query;
116
+ render(results);
117
+ } catch {
118
+ if (current === revision && !controller.signal.aborted) message('Search unavailable');
119
+ } finally {
120
+ if (current === revision) {
121
+ request = undefined;
122
+ list!.removeAttribute('aria-busy');
123
+ }
124
+ }
125
+ }, 240);
126
+ }
127
+ const options = { signal: listeners.signal };
128
+ input.addEventListener('input', search, options);
129
+ input.addEventListener('focus', () => {
130
+ if (renderedQuery === input.value.trim()) show();
131
+ else search();
132
+ }, options);
133
+ input.addEventListener('keydown', event => {
134
+ if (event.isComposing) return;
135
+ if (event.key === 'Escape') { event.preventDefault(); close(); }
136
+ else if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
137
+ event.preventDefault();
138
+ if (panel.hidden && renderedQuery !== input.value.trim()) search();
139
+ else show();
140
+ if (links.length) {
141
+ const next = active < 0 ? (event.key === 'ArrowDown' ? 0 : links.length - 1)
142
+ : (active + (event.key === 'ArrowDown' ? 1 : -1) + links.length) % links.length;
143
+ select(next);
144
+ links[next].scrollIntoView({ block: 'nearest' });
145
+ }
146
+ } else if (event.key === 'Enter' && !panel.hidden && links.length) {
147
+ event.preventDefault();
148
+ links[active < 0 ? 0 : active].click();
149
+ }
150
+ }, options);
151
+ list.addEventListener('pointerdown', event => event.preventDefault(), options);
152
+ list.addEventListener('pointerover', event => {
153
+ const target = event.target instanceof Element ? event.target.closest('a') : null;
154
+ const index = links.findIndex(link => link === target);
155
+ if (index >= 0) select(index);
156
+ }, options);
157
+ document.addEventListener('pointerdown', event => {
158
+ if (event.target instanceof Node && !root.contains(event.target)) close();
159
+ }, options);
160
+ document.addEventListener('focusin', event => {
161
+ if (event.target instanceof Node && !root.contains(event.target)) close();
162
+ }, options);
163
+ document.addEventListener('keydown', event => {
164
+ if (event.key !== '/' || event.defaultPrevented || event.isComposing || event.ctrlKey || event.metaKey || event.altKey) return;
165
+ const target = event.target;
166
+ if (target instanceof Element && target.closest('input, textarea, select, [contenteditable]:not([contenteditable="false"])')) return;
167
+ const details = root.closest('details');
168
+ if (!input.getClientRects().length && !(details && !details.open && details.getClientRects().length)) return;
169
+ event.preventDefault();
170
+ if (details) details.open = true;
171
+ input.focus();
172
+ input.select();
173
+ }, options);
174
+ return () => { close(); listeners.abort(); mounted.delete(root); };
175
+ }
176
+
177
+ /** Idempotent enhancement; cleanup only removes instances created by this call. */
178
+ export function initDocsSearch(scope: ParentNode = document): () => void {
179
+ const roots = Array.from(scope.querySelectorAll<HTMLElement>('[data-docs-search]'));
180
+ if (scope instanceof HTMLElement && scope.matches('[data-docs-search]')) roots.unshift(scope);
181
+ const cleanups: (() => void)[] = [];
182
+ for (const root of roots) {
183
+ if (mounted.has(root)) continue;
184
+ const cleanup = mount(root);
185
+ mounted.set(root, cleanup);
186
+ cleanups.push(cleanup);
187
+ }
188
+ return () => cleanups.forEach(cleanup => cleanup());
189
+ }
190
+
191
+ if (typeof document !== 'undefined') {
192
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => initDocsSearch(), { once: true });
193
+ else initDocsSearch();
194
+ }
@@ -0,0 +1,63 @@
1
+ import { createHash } from 'node:crypto';
2
+
3
+ export const model = '@cf/baai/bge-base-en-v1.5';
4
+ export const pooling = 'cls';
5
+ export const dimensions = 768;
6
+ const digest = value => createHash('sha256').update(value).digest('hex');
7
+
8
+ // Keep long sections inside the model's context. Every part keeps the same
9
+ // heading link; retrieval collapses duplicate links after scoring.
10
+ function parts(text) {
11
+ const chunks = [];
12
+ // Paragraph boundaries are stable cache boundaries. Within a long paragraph,
13
+ // keep sentences together so a short task isn't diluted by an entire guide.
14
+ for (const paragraph of text.split(/\n\n+/).filter(Boolean)) {
15
+ let part = '';
16
+ const sentences = paragraph.split(/(?<=[.!?])\s+/);
17
+ for (const sentence of sentences) {
18
+ if (part && part.length + sentence.length > 650) { chunks.push(part.trim()); part = ''; }
19
+ if (sentence.length > 650) {
20
+ for (const word of sentence.split(/\s+/).filter(Boolean)) {
21
+ if (part && part.length + word.length > 650) { chunks.push(part.trim()); part = ''; }
22
+ if (word.length > 650) {
23
+ if (part) { chunks.push(part.trim()); part = ''; }
24
+ for (let i = 0; i < word.length; i += 650) chunks.push(word.slice(i, i + 650));
25
+ } else part += `${part ? ' ' : ''}${word}`;
26
+ }
27
+ } else part += `${part ? ' ' : ''}${sentence.trim()}`;
28
+ }
29
+ if (part.trim()) chunks.push(part.trim());
30
+ }
31
+ return chunks;
32
+ }
33
+
34
+ export function searchChunks(pages) {
35
+ return pages.flatMap(page => page.searchSections.flatMap(section => parts(section.text).map(text => {
36
+ const href = `${page.href}#${section.anchor}`;
37
+ const hash = digest(JSON.stringify([model, pooling, href, section.titlePath, text]));
38
+ return { ...section, text, href, hash };
39
+ })));
40
+ }
41
+
42
+ export function validVector(vector) {
43
+ return Array.isArray(vector) && vector.length === dimensions && vector.every(Number.isFinite) && vector.some(value => value !== 0);
44
+ }
45
+
46
+ export async function buildSearchIndex(pages, { previous = [], embed, onBatch = () => {} }) {
47
+ const chunks = searchChunks(pages);
48
+ const cached = new Map(previous.filter(index => index?.version === 1 && index.model === model && index.pooling === pooling && index.dimensions === dimensions)
49
+ .flatMap(index => index.chunks).filter(chunk => validVector(chunk.vector)).map(chunk => [chunk.hash, chunk.vector]));
50
+ const missing = chunks.filter(chunk => !cached.has(chunk.hash));
51
+ let embedded = 0;
52
+ for (let offset = 0; offset < missing.length; offset += 32) {
53
+ const batch = missing.slice(offset, offset + 32);
54
+ const response = await embed(model, { text: batch.map(chunk => `${chunk.titlePath.join(' > ')}\n${chunk.text}`), pooling });
55
+ if (response.data?.length !== batch.length || !response.data.every(validVector)) throw Error('Workers AI returned invalid embeddings; search build stopped.');
56
+ batch.forEach((chunk, i) => cached.set(chunk.hash, response.data[i].map(value => Number(value.toFixed(6)))));
57
+ embedded += batch.length;
58
+ onBatch({ embedded, total: missing.length });
59
+ }
60
+ const index = { version: 1, model, pooling, dimensions, corpusHash: digest(chunks.map(chunk => chunk.hash).join('\n')),
61
+ chunks: chunks.map(chunk => ({ ...chunk, vector: cached.get(chunk.hash) })) };
62
+ return { index, counts: { total: chunks.length, reused: chunks.length - embedded, embedded } };
63
+ }
@@ -0,0 +1,16 @@
1
+ import type { SearchIndex, SearchResult } from './types';
2
+
3
+ const magnitude = (vector: number[]) => Math.sqrt(vector.reduce((sum, value) => sum + value * value, 0));
4
+ export function search(index: SearchIndex, query: number[], minimumScore = 0.55): SearchResult[] {
5
+ if (query.length !== index.dimensions || !query.every(Number.isFinite)) throw Error('Invalid query embedding');
6
+ const norm = magnitude(query);
7
+ if (!norm) throw Error('Empty query embedding');
8
+ const ranked = index.chunks.map(chunk => ({
9
+ href: chunk.href,
10
+ titlePath: chunk.titlePath,
11
+ snippet: chunk.text.length > 155 ? `${chunk.text.slice(0, 154).replace(/\s+\S*$/, '')}…` : chunk.text,
12
+ score: chunk.vector.reduce((sum, value, i) => sum + value * query[i], 0) / (norm * magnitude(chunk.vector)),
13
+ })).filter(result => result.score >= minimumScore).sort((a, b) => b.score - a.score);
14
+ const seen = new Set<string>();
15
+ return ranked.filter(result => { if (seen.has(result.href)) return false; seen.add(result.href); return true; }).slice(0, 5);
16
+ }
@@ -0,0 +1,19 @@
1
+ /* Inline results stay inside the sidebar's scroll area and the phone menu. */
2
+ .docs-search { min-width: 0; margin-bottom: 26px; color: var(--ink); }
3
+ .docs-search-label { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0; }
4
+ .docs-search-field { display: flex; align-items: center; gap: 8px; min-width: 0; min-height: 44px; padding: 0 10px; border: 1px solid var(--rule); border-radius: 7px; background: var(--paper); }
5
+ .docs-search-field:focus-within { outline: 2px solid var(--ink); outline-offset: 2px; }
6
+ .docs-search input { display: block; width: 100%; min-width: 0; min-height: 42px; padding: 8px 0; border: 0; border-radius: 0; outline: none; background: transparent; color: var(--ink); font: inherit; font-size: 15px; line-height: 1.4; }
7
+ .docs-search input::-webkit-search-cancel-button { filter: grayscale(1); }
8
+ .docs-search input::placeholder { color: var(--ink-soft); opacity: 1; }
9
+ .docs-search kbd { flex: none; padding: 0 5px; border: 1px solid var(--rule); border-radius: 3px; color: var(--ink-soft); font: inherit; font-size: 12px; line-height: 20px; }
10
+ .docs-search-panel { margin-top: 10px; }
11
+ .docs-search-status { margin: 0; color: var(--ink-soft); font-size: 14px; line-height: 1.4; }
12
+ .docs-search-status:empty { display: none; }
13
+ .docs-search-results { display: grid; margin: 0; padding: 0; list-style: none; }
14
+ .docs-search-results li { min-width: 0; border-bottom: 1px solid var(--rule); }
15
+ .docs-search-results a { display: block; min-width: 0; padding: 10px 5px; border-radius: 3px; color: var(--ink); text-decoration: none; }
16
+ .docs-search-results a:is(:hover, [aria-selected="true"]) { outline: 1px solid var(--ink); outline-offset: -1px; }
17
+ .docs-search-result-title { display: block; font-size: 14px; font-weight: 500; line-height: 1.4; overflow-wrap: anywhere; }
18
+ .docs-search-result-snippet { display: block; overflow: hidden; margin-top: 3px; color: var(--ink-soft); font-size: 13px; line-height: 1.4; text-overflow: ellipsis; white-space: nowrap; }
19
+ .docs-search [hidden] { display: none; }
@@ -0,0 +1,24 @@
1
+ import type { SearchSection } from './types';
2
+
3
+ // Run on the renderer's tree after it assigns ids. Search can only link to
4
+ // headings the published page actually has, including duplicate heading ids.
5
+ type Node = { type: string; value?: string; tagName?: string; properties?: Record<string, unknown>; children?: Node[] };
6
+ const textOf = (node: Node): string => node.value ?? (node.children ?? []).map(textOf).join('');
7
+ const collapse = (text: string) => text.replace(/\s+/g, ' ').trim();
8
+
9
+ export function headingSections(nodes: Node[], title: string, titleId: string): SearchSection[] {
10
+ const sections: SearchSection[] = [];
11
+ let parent = '';
12
+ let current: SearchSection = { anchor: titleId, titlePath: [title], text: '' };
13
+ const finish = () => { if (current.text.trim()) sections.push({ ...current, text: current.text.trim() }); };
14
+ for (const node of nodes) {
15
+ if (node.tagName === 'h2' || node.tagName === 'h3') {
16
+ finish();
17
+ const heading = collapse(textOf(node));
18
+ if (node.tagName === 'h2') parent = heading;
19
+ current = { anchor: String(node.properties?.id), titlePath: [title, ...(node.tagName === 'h3' && parent ? [parent] : []), heading], text: '' };
20
+ } else current.text += `${collapse(textOf(node))}\n\n`;
21
+ }
22
+ finish();
23
+ return sections;
24
+ }
@@ -0,0 +1,14 @@
1
+ export type SearchSection = { anchor: string; titlePath: string[]; text: string };
2
+ export type SearchPage = { href: string; searchSections: SearchSection[] };
3
+ export type SearchChunk = SearchSection & { href: string; hash: string };
4
+ export type SearchIndex = {
5
+ version: 1;
6
+ model: string;
7
+ pooling: 'cls';
8
+ dimensions: number;
9
+ corpusHash: string;
10
+ chunks: (SearchChunk & { vector: number[] })[];
11
+ };
12
+ export type Embeddings = { shape: number[]; data: number[][] };
13
+ export type Embed = (model: string, input: { text: string[]; pooling: 'cls' }) => Promise<Embeddings>;
14
+ export type SearchResult = { href: string; titlePath: string[]; snippet: string; score: number };
@@ -0,0 +1,39 @@
1
+ import { search } from './retrieve';
2
+ import type { Embed, SearchIndex } from './types';
3
+
4
+ type Environment = { ASSETS: { fetch(request: Request): Promise<Response> }; AI: { run: Embed } };
5
+ const json = (data: unknown, status = 200) => Response.json(data, { status, headers: { 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' } });
6
+
7
+ /** No app state, credentials or database. Install on the site's Worker only. */
8
+ export function createSearchWorker({ corpusHash, endpoint = '/docs/search', minimumScore = 0.55, indexAsset = '/docs-search-vectors.json', model = '@cf/baai/bge-base-en-v1.5', pooling = 'cls' }: { corpusHash: string; endpoint?: string; minimumScore?: number; indexAsset?: string; model?: string; pooling?: string }) {
9
+ let loaded: SearchIndex | undefined;
10
+ async function load(request: Request, env: Environment): Promise<SearchIndex> {
11
+ if (loaded) return loaded;
12
+ const response = await env.ASSETS.fetch(new Request(new URL(indexAsset, request.url)));
13
+ if (!response.ok) throw Error('Search index unavailable');
14
+ const index = await response.json() as SearchIndex;
15
+ if (index.corpusHash !== corpusHash || index.version !== 1 || index.pooling !== pooling || index.model !== model || !index.dimensions || !Array.isArray(index.chunks)) throw Error('Invalid search index');
16
+ loaded = index;
17
+ return index;
18
+ }
19
+ return {
20
+ async fetch(request: Request, env: Environment): Promise<Response> {
21
+ const url = new URL(request.url);
22
+ if (url.hostname.startsWith('www.')) return Response.redirect(`https://${url.hostname.slice(4)}${url.pathname}${url.search}`, 301);
23
+ if (url.pathname !== endpoint) return env.ASSETS.fetch(request);
24
+ if (request.method !== 'GET') return json({ error: 'Method not allowed' }, 405);
25
+ const query = (url.searchParams.get('q') ?? '').trim();
26
+ if (query.length < 2) return json({ results: [] });
27
+ if (query.length > 240) return json({ error: 'Query too long' }, 400);
28
+ try {
29
+ // The generated entry contains the corpus digest, so docs changes also
30
+ // change Worker code. Binding-only isolate reuse cannot retain old vectors.
31
+ const index = await load(request, env);
32
+ const vectors = await env.AI.run(index.model, { text: [`Represent this sentence for searching relevant passages: ${query}`], pooling: index.pooling });
33
+ return json({ results: search(index, vectors.data[0], minimumScore) });
34
+ } catch {
35
+ return json({ error: 'Search unavailable' }, 503);
36
+ }
37
+ },
38
+ };
39
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runeditrun/rer",
3
- "version": "0.2.74",
3
+ "version": "0.2.75",
4
4
  "description": "The rer command: install, set up, run and launch Run Edit Run checkouts.",
5
5
  "license": "MIT",
6
6
  "type": "module",