@runeditrun/rer 0.2.15 → 0.2.17

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,41 +1,77 @@
1
- import { readdir, readFile } from 'node:fs/promises';
2
- import { join, relative, sep } from 'node:path';
3
- import { createRequire } from 'node:module';
4
- import { pathToFileURL } from 'node:url';
5
- export async function checkBoundary(root, { engine='node', cacheContract }={}) {
6
- const ts=await import(pathToFileURL(createRequire(join(root,'package.json')).resolve('typescript'))), failures=[];
7
- async function walk(directory){
8
- for(const item of await readdir(directory,{withFileTypes:true})){
9
- const path=join(directory,item.name);if(item.isDirectory()){await walk(path);continue;}if(!/\.[cm]?[jt]sx?$/.test(item.name))continue;
10
- const name=relative(root,path),tree=ts.createSourceFile(path,await readFile(path,'utf8'),ts.ScriptTarget.Latest,true);
11
- const cache=cacheContract==='lamp-retained-v1'&&/(?:^|\/)platform\/blobs\/snapshot-cache\.ts$/.test(name);
12
- const bindings=/(?:^|\/)platform\/bindings\.server\.ts$/.test(name);
1
+ import { relative, sep } from 'node:path';
2
+ import { configuredEntry, walkImportGraph } from './import-graph.mjs';
3
+
4
+ export async function checkBoundary(root, { engine='node', cacheContract, entries, emittedFiles, outputRoot }={}) {
5
+ const failures = [];
6
+ if (Boolean(emittedFiles) !== Boolean(outputRoot)) throw new Error('Emitted files and output root must be supplied together');
7
+ const roots = entries ?? [await configuredEntry(root)];
8
+ if (!Array.isArray(roots) || !roots.length) throw new Error('At least one app entry is required');
9
+ const graph = await walkImportGraph(root, {
10
+ entries: roots,
11
+ emittedFiles,
12
+ outputRoot,
13
+ onFile({ ts, tree, path }) {
14
+ const name = relative(root, path).split(sep).join('/');
15
+ const cache = cacheContract === 'lamp-retained-v1' && /(?:^|\/)platform\/blobs\/snapshot-cache\.ts$/.test(name);
16
+ const bindings = /(?:^|\/)platform\/bindings\.server\.ts$/.test(name);
13
17
  // The demo guard an exported seed carries reads RER_DEMO from env: that one
14
18
  // file, and only its unrenamed `env` import.
15
- const demo=name.split(sep).join('/')==='src/modules/demo/index.mjs';
16
- const fail=api=>failures.push({path:name,api}),localNames=new Set();
17
- function names(node){if((ts.isVariableDeclaration(node)||ts.isFunctionDeclaration(node)||ts.isImportSpecifier(node))&&node.name&&ts.isIdentifier(node.name))localNames.add(node.name.text);ts.forEachChild(node,names);}names(tree);
18
- function visit(node){
19
- if((ts.isImportDeclaration(node)||ts.isExportDeclaration(node))&&node.moduleSpecifier&&ts.isStringLiteral(node.moduleSpecifier)){
20
- const module=node.moduleSpecifier.text;
21
- if(module.startsWith('cloudflare:')){
22
- const imports=node.importClause?.namedBindings;
23
- const allowed=module==='cloudflare:workers'&&imports&&ts.isNamedImports(imports)&&imports.elements.every(element=>(demo&&!node.importClause.name&&!element.propertyName&&element.name.text==='env')||(bindings&&(element.propertyName??element.name).text==='env')||(cache&&(element.propertyName??element.name).text==='DurableObject'));
24
- if(!allowed&&!(engine==='workerd'&&module==='cloudflare:workers'))fail('Cloudflare import outside binding/cache contract');
19
+ const demo = name === 'src/modules/demo/index.mjs';
20
+ const fail = api => failures.push({ path:name, api }), localNames = new Set();
21
+ function collectNames(node) {
22
+ if ((ts.isVariableDeclaration(node) || ts.isFunctionDeclaration(node) || ts.isImportSpecifier(node)) && node.name && ts.isIdentifier(node.name)) localNames.add(node.name.text);
23
+ ts.forEachChild(node, collectNames);
24
+ }
25
+ collectNames(tree);
26
+ function visit(node) {
27
+ const runtimeDeclaration = declaration => {
28
+ if (ts.isImportDeclaration(declaration)) {
29
+ const clause = declaration.importClause;
30
+ if (!clause) return true;
31
+ if (clause.isTypeOnly) return false;
32
+ if (clause.name) return true;
33
+ const bindings = clause.namedBindings;
34
+ return !bindings || ts.isNamespaceImport(bindings) || bindings.elements.length === 0 || bindings.elements.some(element => !element.isTypeOnly);
35
+ }
36
+ if (ts.isExportDeclaration(declaration)) {
37
+ if (declaration.isTypeOnly) return false;
38
+ const clause = declaration.exportClause;
39
+ return !clause || !ts.isNamedExports(clause) || clause.elements.length === 0 || clause.elements.some(element => !element.isTypeOnly);
40
+ }
41
+ return false;
42
+ };
43
+ if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && runtimeDeclaration(node) && node.moduleSpecifier && ts.isStringLiteralLike(node.moduleSpecifier)) {
44
+ const module = node.moduleSpecifier.text;
45
+ if (module.startsWith('cloudflare:')) {
46
+ const imports = node.importClause?.namedBindings;
47
+ const runtimeImports = imports && ts.isNamedImports(imports) ? imports.elements.filter(element => !element.isTypeOnly) : [];
48
+ const allowed = module === 'cloudflare:workers' && runtimeImports.length > 0 && imports && ts.isNamedImports(imports) && runtimeImports.every(element =>
49
+ (demo && !node.importClause.name && !element.propertyName && element.name.text === 'env') ||
50
+ (bindings && (element.propertyName ?? element.name).text === 'env') ||
51
+ (cache && (element.propertyName ?? element.name).text === 'DurableObject'));
52
+ if (!allowed && !(engine === 'workerd' && module === 'cloudflare:workers')) fail('Cloudflare import outside binding/cache contract');
25
53
  }
26
54
  }
27
- if(ts.isCallExpression(node)&&node.arguments.some((arg,index)=>ts.isStringLiteral(arg)&&arg.text.startsWith('cloudflare:')&&!(engine==='workerd'&&node.expression.kind===ts.SyntaxKind.ImportKeyword&&index===0&&arg.text==='cloudflare:workers')))fail('Dynamic Cloudflare import');
28
- if(ts.isIdentifier(node)&&engine!=='workerd'&&['WebSocketPair','passThroughOnException','timingSafeEqual','HTMLRewriter'].includes(node.text))fail(node.text);
29
- if(ts.isCallExpression(node)&&ts.isIdentifier(node.expression)&&node.expression.text==='email'&&!localNames.has('email'))fail('email()');
30
- if(ts.isPropertyAccessExpression(node)&&((node.expression.getText(tree)==='caches'&&node.name.text==='default')||(node.expression.getText(tree)==='request'&&node.name.text==='cf')))fail(node.getText(tree));
31
- if(ts.isElementAccessExpression(node)&&ts.isStringLiteral(node.argumentExpression)&&((node.expression.getText(tree)==='caches'&&node.argumentExpression.text==='default')||(node.expression.getText(tree)==='request'&&node.argumentExpression.text==='cf')))fail(node.getText(tree));
32
- if(engine!=='workerd'&&ts.isHeritageClause(node)&&node.token===ts.SyntaxKind.ExtendsKeyword&&node.types.some(type=>/DurableObject/.test(type.expression.getText(tree)))&&!cache)fail('New Durable Object');
33
- ts.forEachChild(node,visit);
55
+ if (ts.isImportEqualsDeclaration(node) && !node.isTypeOnly && ts.isExternalModuleReference(node.moduleReference) && ts.isStringLiteralLike(node.moduleReference.expression) && node.moduleReference.expression.text.startsWith('cloudflare:')) fail('Dynamic Cloudflare import');
56
+ if (ts.isCallExpression(node) && node.arguments[0] && ts.isStringLiteralLike(node.arguments[0])) {
57
+ const module = node.arguments[0].text;
58
+ const isDynamicImport = node.expression.kind === ts.SyntaxKind.ImportKeyword;
59
+ const isRequire = ts.isIdentifier(node.expression) && node.expression.text === 'require';
60
+ if ((isDynamicImport || isRequire) && module.startsWith('cloudflare:') && !(engine === 'workerd' && isDynamicImport && module === 'cloudflare:workers')) fail('Dynamic Cloudflare import');
61
+ }
62
+ if (ts.isIdentifier(node) && engine !== 'workerd' && ['WebSocketPair','passThroughOnException','timingSafeEqual','HTMLRewriter'].includes(node.text)) fail(node.text);
63
+ if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === 'email' && !localNames.has('email')) fail('email()');
64
+ if (ts.isPropertyAccessExpression(node) && ((node.expression.getText(tree) === 'caches' && node.name.text === 'default') || (node.expression.getText(tree) === 'request' && node.name.text === 'cf'))) fail(node.getText(tree));
65
+ if (ts.isElementAccessExpression(node) && ts.isStringLiteral(node.argumentExpression) && ((node.expression.getText(tree) === 'caches' && node.argumentExpression.text === 'default') || (node.expression.getText(tree) === 'request' && node.argumentExpression.text === 'cf'))) fail(node.getText(tree));
66
+ if (engine !== 'workerd' && ts.isHeritageClause(node) && node.token === ts.SyntaxKind.ExtendsKeyword && node.types.some(type => /DurableObject/.test(type.expression.getText(tree))) && !cache) fail('New Durable Object');
67
+ ts.forEachChild(node, visit);
34
68
  }
35
69
  visit(tree);
36
- }
37
- }
38
- await walk(join(root,'src'));
39
- if(failures.length){const cause=new Error('Container import boundary failed');cause.failures=failures;throw cause;}
40
- return {engine,ok:true};
70
+ },
71
+ });
72
+ failures.push(...graph.failures);
73
+ if (failures.length) { const cause = new Error('Container import boundary failed'); cause.failures = failures; throw cause; }
74
+ return { engine, ok:true };
41
75
  }
76
+
77
+ export { configuredEntry };
@@ -1,5 +1,5 @@
1
1
  import { readFile, writeFile, readdir, realpath, cp, mkdir, rm } from 'node:fs/promises';
2
- import { dirname, join, resolve } from 'node:path';
2
+ import { dirname, join, resolve, sep } from 'node:path';
3
3
  import { createRequire } from 'node:module';
4
4
  import { pathToFileURL } from 'node:url';
5
5
  import { createHash } from 'node:crypto';
@@ -23,10 +23,18 @@ async function buildImage(root, { output = join(root,'.rer/container/image'), en
23
23
  if (!loaded) throw new Error('Vite configuration missing');
24
24
  const config = loaded.config;
25
25
  const outputExports = new Map();
26
+ const freshServerFiles = new Set(), serverOutput = resolve(root,'dist/server');
26
27
  if (engine === 'workerd') config.plugins = [...(config.plugins ?? []), {
27
28
  name:'rer-container-exports',
28
29
  async writeBundle(output,bundle) {
29
- for (const chunk of Object.values(bundle)) if (chunk.type === 'chunk' && chunk.isEntry) outputExports.set(await realpath(resolve(root,output.dir ?? dirname(output.file),chunk.fileName)),new Set(chunk.exports));
30
+ const outputDir = resolve(root,output.dir ?? dirname(output.file));
31
+ if (outputDir === serverOutput || outputDir.startsWith(serverOutput + sep)) {
32
+ for (const chunk of Object.values(bundle)) if (chunk.type === 'chunk') {
33
+ const path = resolve(outputDir,chunk.fileName);
34
+ freshServerFiles.add(path);
35
+ if (chunk.isEntry) outputExports.set(await realpath(path),new Set(chunk.exports));
36
+ }
37
+ }
30
38
  },
31
39
  }];
32
40
  if (engine === 'node') {
@@ -35,7 +43,13 @@ async function buildImage(root, { output = join(root,'.rer/container/image'), en
35
43
  config.plugins = [{ name:'rer-container-bindings', enforce:'pre',
36
44
  resolveId(id) { if (id === 'cloudflare:workers') return bindingShim; },
37
45
  transform(source,id) { if (cacheContract === 'lamp-retained-v1' && id === join(root,'src/server.ts')) return source.replace(/export\s*\{\s*SnapshotCache\s*\}\s*from\s*['"][^'"]+['"];?/,''); },
38
- },...plugins];
46
+ },...plugins,{
47
+ name:'rer-container-boundary-output',
48
+ writeBundle(output,bundle) {
49
+ const outputDir = resolve(root,output.dir ?? dirname(output.file));
50
+ if (outputDir === serverOutput || outputDir.startsWith(serverOutput + sep)) for (const chunk of Object.values(bundle)) if (chunk.type === 'chunk') freshServerFiles.add(resolve(outputDir,chunk.fileName));
51
+ },
52
+ }];
39
53
  config.ssr = { ...config.ssr,noExternal:true }; config.environments = { ...config.environments,ssr:{ ...config.environments?.ssr,resolve:{ noExternal:true },build:{ ...config.environments?.ssr?.build,rolldownOptions:{ output:{ entryFileNames:'index.mjs' } } } } };
40
54
  }
41
55
  const builder = await vite.createBuilder({ ...config,root,configFile:false }); await builder.buildApp();
@@ -47,6 +61,9 @@ async function buildImage(root, { output = join(root,'.rer/container/image'), en
47
61
  localDurableObjects(workerConfig,outputExports.get(await realpath(resolve(root,'dist/server',workerConfig.main))));
48
62
  }
49
63
  else workerConfig = parseJsonc(await readFile(join(root,'wrangler.jsonc'),'utf8'));
64
+ const serverEntry = engine === 'workerd' ? resolve(root,'dist/server',workerConfig.main) : resolve(root,'dist/server/index.mjs');
65
+ if (!freshServerFiles.has(serverEntry)) throw new Error('Container server entry was not emitted by this build');
66
+ await checkBoundary(root,{engine,cacheContract,entries:[serverEntry],emittedFiles:freshServerFiles,outputRoot:serverOutput});
50
67
  const { unstable_splitSqlQuery:split } = require('wrangler');
51
68
  const migrations = {}, rewrites = await readMigrationRewrites(root);
52
69
  for (const db of workerConfig.d1_databases ?? []) {
@@ -0,0 +1,233 @@
1
+ import { readFile, stat } from 'node:fs/promises';
2
+ import { createRequire } from 'node:module';
3
+ import { dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
4
+ import { fileURLToPath, pathToFileURL } from 'node:url';
5
+ import { parseJsonc } from '../../cli/jsonc.mjs';
6
+ import { tomlMain } from '../../cli/deploy-config.mjs';
7
+
8
+ const sourceExtensions = new Set(['.js', '.jsx', '.mjs', '.cjs', '.ts', '.tsx', '.mts', '.cts']);
9
+ const builtExtensions = ['.mjs', '.js', '.cjs', '.jsx'];
10
+
11
+ const normalized = path => resolve(path);
12
+ const displayPath = (root, path) => relative(root, path).split(sep).join('/') || '.';
13
+ const isDeclaration = path => /\.d\.(?:ts|mts|cts)$/i.test(path);
14
+ const isCode = path => sourceExtensions.has(extname(path).toLowerCase()) && !isDeclaration(path);
15
+ const isPackagePath = path => path.split(sep).includes('node_modules');
16
+ const stripQuery = specifier => specifier.startsWith('#') ? specifier : specifier.split(/[?#]/, 1)[0];
17
+ const isRelative = specifier => specifier.startsWith('./') || specifier.startsWith('../');
18
+ const isScheme = specifier => /^[a-z][a-z\d+.-]*:/i.test(specifier);
19
+
20
+ function runtimeImport(ts, declaration) {
21
+ const clause = declaration.importClause;
22
+ if (!clause) return true;
23
+ if (clause.isTypeOnly) return false;
24
+ if (clause.name) return true;
25
+ const bindings = clause.namedBindings;
26
+ if (!bindings || ts.isNamespaceImport(bindings)) return Boolean(bindings);
27
+ return bindings.elements.length === 0 || bindings.elements.some(element => !element.isTypeOnly);
28
+ }
29
+
30
+ function runtimeReexport(ts, declaration) {
31
+ if (declaration.isTypeOnly) return false;
32
+ const clause = declaration.exportClause;
33
+ return !clause || !ts.isNamedExports(clause) || clause.elements.length === 0 || clause.elements.some(element => !element.isTypeOnly);
34
+ }
35
+
36
+ function runtimeEdges(ts, tree, options) {
37
+ const edges = [];
38
+ const add = (node, kind) => {
39
+ if (node && ts.isStringLiteralLike(node)) {
40
+ // Dynamic import keeps its ESM condition inside a CommonJS module; static
41
+ // TypeScript imports follow that file's emitted format instead.
42
+ const mode = kind === 'require' || kind === 'import-equals' ? ts.ModuleKind.CommonJS
43
+ : kind === 'dynamic-import' ? ts.ModuleKind.ESNext
44
+ : ts.getModeForUsageLocation(tree, node, options) ?? ts.ModuleKind.ESNext;
45
+ edges.push({ specifier: node.text, kind, mode });
46
+ }
47
+ };
48
+ function visit(node) {
49
+ if (ts.isImportDeclaration(node) && runtimeImport(ts, node)) add(node.moduleSpecifier, 'import');
50
+ else if (ts.isExportDeclaration(node) && node.moduleSpecifier && runtimeReexport(ts, node)) add(node.moduleSpecifier, 're-export');
51
+ else if (ts.isImportEqualsDeclaration(node) && !node.isTypeOnly && ts.isExternalModuleReference(node.moduleReference)) add(node.moduleReference.expression, 'import-equals');
52
+ else if (ts.isCallExpression(node)) {
53
+ if (node.expression.kind === ts.SyntaxKind.ImportKeyword) add(node.arguments[0], 'dynamic-import');
54
+ else if (ts.isIdentifier(node.expression) && node.expression.text === 'require') add(node.arguments[0], 'require');
55
+ }
56
+ ts.forEachChild(node, visit);
57
+ }
58
+ visit(tree);
59
+ return edges;
60
+ }
61
+
62
+ function matchesPathAlias(specifier, options) {
63
+ for (const pattern of Object.keys(options.paths ?? {})) {
64
+ const wildcard = pattern.indexOf('*');
65
+ if (wildcard < 0 ? specifier === pattern : specifier.startsWith(pattern.slice(0, wildcard)) && specifier.endsWith(pattern.slice(wildcard + 1))) return true;
66
+ }
67
+ return false;
68
+ }
69
+
70
+ async function localAssetExists(from, specifier) {
71
+ const target = resolve(dirname(from), specifier);
72
+ try { return (await stat(target)).isFile() ? target : null; } catch (error) { if (error.code === 'ENOENT' || error.code === 'ENOTDIR') return null; throw error; }
73
+ }
74
+
75
+ async function loadTypeScript(root) {
76
+ const require = createRequire(join(root, 'package.json'));
77
+ const path = require.resolve('typescript');
78
+ return import(pathToFileURL(path));
79
+ }
80
+
81
+ async function compilerOptions(root, ts) {
82
+ const path = join(root, 'tsconfig.json');
83
+ if (!ts.sys.fileExists(path)) return { allowJs: true, resolveJsonModule: true, module: ts.ModuleKind.ESNext, moduleResolution: ts.ModuleResolutionKind.Bundler };
84
+ try {
85
+ const parsed = ts.getParsedCommandLineOfConfigFile(path, {}, {
86
+ ...ts.sys,
87
+ onUnRecoverableConfigFileDiagnostic(diagnostic) {
88
+ throw new Error(ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'));
89
+ },
90
+ });
91
+ if (!parsed) throw new Error('TypeScript did not return parsed compiler options');
92
+ const errors = parsed.errors.filter(diagnostic => diagnostic.category === ts.DiagnosticCategory.Error);
93
+ if (errors.length) throw new Error(errors.map(diagnostic => ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')).join('\n'));
94
+ return { ...parsed.options, allowJs: true, resolveJsonModule: true };
95
+ } catch (error) {
96
+ if (error.code === 'ENOENT') return { allowJs: true, resolveJsonModule: true, module: ts.ModuleKind.ESNext, moduleResolution: ts.ModuleResolutionKind.Bundler };
97
+ throw new Error(`Could not read TypeScript project configuration: ${error.message}`, { cause: error });
98
+ }
99
+ }
100
+
101
+ async function configuredEntry(root) {
102
+ for (const name of ['wrangler.jsonc', 'wrangler.json', 'wrangler.toml']) {
103
+ let text;
104
+ try { text = await readFile(join(root, name), 'utf8'); }
105
+ catch (error) { if (error.code === 'ENOENT') continue; throw error; }
106
+ let main;
107
+ try {
108
+ main = name.endsWith('.toml') ? tomlMain(text) : parseJsonc(text).main;
109
+ } catch (error) {
110
+ throw new Error(`Could not read Wrangler main from ${name}: ${error.message}`, { cause: error });
111
+ }
112
+ if (typeof main !== 'string' || !main.trim()) throw new Error(`${name} does not declare a Wrangler main entry`);
113
+ return resolve(root, main);
114
+ }
115
+ throw new Error('No root wrangler.jsonc, wrangler.json, or wrangler.toml declares the app main entry');
116
+ }
117
+
118
+ function failure(path, api, extra = {}) {
119
+ return { path, api, ...extra };
120
+ }
121
+
122
+ function runtimeRequest(specifier) {
123
+ return /^file:/i.test(specifier) ? fileURLToPath(specifier) : stripQuery(specifier);
124
+ }
125
+
126
+ async function resolveSourceEdge(ts, edge, importer, options) {
127
+ const { specifier, mode } = edge;
128
+ let request;
129
+ try { request = runtimeRequest(specifier); }
130
+ catch { return { unresolved: true, reason: 'invalid local file URL' }; }
131
+ const local = isRelative(request) || isAbsolute(request) || request.startsWith('#') || matchesPathAlias(request, options);
132
+ if (isScheme(request)) return { external: true };
133
+ const javascriptRequest = builtExtensions.includes(extname(request).toLowerCase());
134
+ if (javascriptRequest && (isRelative(request) || isAbsolute(request))) {
135
+ const implementation = await localAssetExists(importer, request);
136
+ if (implementation) return isPackagePath(implementation) ? { external: true } : { path: implementation };
137
+ }
138
+ // TypeScript prefers declaration sidecars to JavaScript implementations. They
139
+ // describe types, not the code the runtime will execute, so exclude them from
140
+ // graph resolution. Explicit JavaScript imports first try real JavaScript;
141
+ // the second pass retains TypeScript's extension substitution for source apps
142
+ // that import ./module.js but author module.ts (including configured aliases).
143
+ const implementationHost = { ...ts.sys, fileExists: path => !isDeclaration(path) && ts.sys.fileExists(path) };
144
+ const javascriptHost = { ...ts.sys, fileExists: path => !/\.(?:ts|tsx|mts|cts)$/i.test(path) && ts.sys.fileExists(path) };
145
+ const resolveModule = host => ts.resolveModuleName(request, importer, options, host, undefined, undefined, mode).resolvedModule;
146
+ const resolved = (javascriptRequest && resolveModule(javascriptHost)) || resolveModule(implementationHost);
147
+ if (resolved) {
148
+ const path = normalized(resolved.resolvedFileName);
149
+ if (resolved.isExternalLibraryImport || isPackagePath(path)) return { external: true };
150
+ if (isCode(path)) return { path };
151
+ return { external: true };
152
+ }
153
+ if (!local) return { external: true };
154
+ const asset = await localAssetExists(importer, request);
155
+ if (asset && !isCode(asset) && !isDeclaration(asset)) return { external: true };
156
+ return { unresolved: true };
157
+ }
158
+
159
+ async function builtCandidates(importer, request) {
160
+ const target = resolve(dirname(importer), request);
161
+ if (extname(target)) return [target];
162
+ return [...builtExtensions.map(extension => target + extension), ...builtExtensions.map(extension => join(target, 'index' + extension))];
163
+ }
164
+
165
+ function emittedModule(path, emittedFiles, outputRoot) {
166
+ const canonical = normalized(path), rel = relative(outputRoot, canonical);
167
+ if (rel.startsWith('..') || isAbsolute(rel)) return { unresolved: true, reason: 'local import escapes the built server output' };
168
+ if (!emittedFiles.has(canonical)) return { unresolved: true, reason: 'local import was not emitted by this build' };
169
+ return { path: canonical };
170
+ }
171
+
172
+ async function resolveBuiltEdge(ts, importer, edge, options, emittedFiles, outputRoot) {
173
+ let request;
174
+ try { request = runtimeRequest(edge.specifier); }
175
+ catch { return { unresolved: true, reason: 'invalid local file URL' }; }
176
+ if (!isScheme(request) && !isRelative(request) && !isAbsolute(request)) {
177
+ const result = await resolveSourceEdge(ts, edge, importer, options);
178
+ return result.path ? emittedModule(result.path, emittedFiles, outputRoot) : result;
179
+ }
180
+ if (isScheme(request)) return { external: true };
181
+ const requested = resolve(dirname(importer), request);
182
+ const candidates = await builtCandidates(importer, request);
183
+ for (const candidate of candidates) {
184
+ try {
185
+ if (!(await stat(candidate)).isFile()) continue;
186
+ } catch (error) { if (error.code === 'ENOENT' || error.code === 'ENOTDIR') continue; throw error; }
187
+ if (!isCode(candidate)) return { external: true };
188
+ return emittedModule(candidate, emittedFiles, outputRoot);
189
+ }
190
+ if (extname(requested) && !sourceExtensions.has(extname(requested).toLowerCase())) {
191
+ const asset = await localAssetExists(importer, request);
192
+ if (asset) return { external: true };
193
+ }
194
+ return { unresolved: true };
195
+ }
196
+
197
+ export async function walkImportGraph(root, { entries, emittedFiles, outputRoot, onFile }) {
198
+ // A package's `types` condition must not select a different runtime branch.
199
+ const ts = await loadTypeScript(root), options = { ...await compilerOptions(root, ts), noDtsResolution: true };
200
+ const failures = [], visited = new Set(), pending = (await Promise.all(entries.map(async entry => {
201
+ if (isAbsolute(entry)) return normalized(entry);
202
+ return resolve(root, entry);
203
+ }))).reverse();
204
+ const emitted = emittedFiles ? new Set([...emittedFiles].map(normalized)) : null;
205
+ const builtRoot = outputRoot ? normalized(outputRoot) : null;
206
+ const built = Boolean(emitted && builtRoot);
207
+
208
+ while (pending.length) {
209
+ const path = pending.pop(), canonical = normalized(path);
210
+ if (visited.has(canonical)) continue;
211
+ visited.add(canonical);
212
+ let source;
213
+ try { source = await readFile(canonical, 'utf8'); }
214
+ catch (error) { failures.push(failure(displayPath(root, canonical), 'Missing app entry or runtime module', { message: error.message })); continue; }
215
+ if (!isCode(canonical)) { failures.push(failure(displayPath(root, canonical), 'App graph entry is not a JavaScript or TypeScript module')); continue; }
216
+ const tree = ts.createSourceFile(canonical, source, ts.ScriptTarget.Latest, true);
217
+ tree.impliedNodeFormat = ts.getImpliedNodeFormatForFile(canonical, undefined, ts.sys, options);
218
+ onFile?.({ ts, tree, path: canonical, source });
219
+ // Emitted JavaScript already contains its runtime syntax; do not apply the
220
+ // source project's TypeScript module transform to it again.
221
+ for (const edge of runtimeEdges(ts, tree, built ? { ...options, module: ts.ModuleKind.Preserve } : options)) {
222
+ const result = built
223
+ ? await resolveBuiltEdge(ts, canonical, edge, options, emitted, builtRoot)
224
+ : await resolveSourceEdge(ts, edge, canonical, options);
225
+ if (result.unresolved) {
226
+ failures.push(failure(displayPath(root, canonical), 'Unresolved local runtime import', { specifier: edge.specifier, kind: edge.kind, ...(result.reason ? { message: result.reason } : {}) }));
227
+ } else if (result.path) pending.push(result.path);
228
+ }
229
+ }
230
+ return { ts, files: visited, failures };
231
+ }
232
+
233
+ export { configuredEntry, isCode };
@@ -2,7 +2,8 @@
2
2
 
3
3
  The front Worker `rer deploy --demo` deploys at `demo.<domain>` for a seed
4
4
  that adopted demo mode (`withDemo`, export/DEMO.md). `plan.mjs` turns `deploy-demo.json`
5
- into the Worker's Wrangler configuration; the CLI (`cli/demo-host.mjs`) writes
5
+ (optionally `instanceType`, one of Cloudflare's predefined Container instance
6
+ types, `basic` unless set) into the Worker's Wrangler configuration; the CLI (`cli/demo-host.mjs`) writes
6
7
  it with these files and the seed's container image folder (workerd engine) to
7
8
  `.rer/demo-host/` and runs `wrangler deploy` there.
8
9
 
@@ -21,6 +22,12 @@ it with these files and the seed's container image folder (workerd engine) to
21
22
  (`claim.mjs`) to `/auth/owner-claim`. Its alarm ends the demo at its hour or
22
23
  after 15 idle minutes: `destroy()`, `deleteAll()` and the place released. A
23
24
  container that stops by itself ends its demo too.
25
+ The platform stops a container about two minutes after its Durable Object's
26
+ last event, when it evicts the object (and the object's exit watcher with
27
+ it). So the alarm stays in flight until the demo's next check, at most three
28
+ minutes, and arms the next at once, as the Containers class keeps its own
29
+ object alive. A request or alarm that finds the container gone ends the demo
30
+ and answers the ended page (410), never a 5xx.
24
31
  - `capacity.mjs`: `DemoCapacity` admits at most `max_instances` live demos.
25
32
  - `pages.mjs`: the start and ended pages (12ui designs), strict CSP.
26
33
  `start-script.mjs` is the start page's script: once Turnstile passes it
@@ -9,6 +9,11 @@ import { endedPage, clearCookie } from './pages.mjs';
9
9
  // engine's egress worker refuse every send. The front signs the owner in
10
10
  // through the existing signed owner claim. The demo ends at its hour or after
11
11
  // 15 idle minutes: the alarm destroys the container and deletes everything.
12
+ // The platform stops a container about two minutes after its Durable Object's
13
+ // last event, when the object is evicted, and the exit watcher goes with it.
14
+ // So the alarm stays in flight until the demo's next check and then arms the
15
+ // next at once, as the Containers class keeps its object alive; a container
16
+ // that is gone anyway answers the ended page and frees its place.
12
17
  const PORT = 8080, IDLE = 15 * 60_000, OWNER = 'owner@demo.invalid';
13
18
  // The container's port speaks plain HTTP; the app takes its public origin from RER_INGRESS_ORIGIN.
14
19
  const inside = url => `http://container${url.pathname}${url.search}`;
@@ -40,6 +45,7 @@ export class DemoContainer extends DurableObject {
40
45
  startTimeout = 120_000;
41
46
  probeTimeout = 5000;
42
47
  cleanupRetry = 30_000;
48
+ hold = 3 * 60_000;
43
49
  get container() { return this.ctx.container; }
44
50
  port() { return this.container.getTcpPort(PORT); }
45
51
 
@@ -49,13 +55,13 @@ export class DemoContainer extends DurableObject {
49
55
  const deadline = this.started + this.startTimeout;
50
56
  const id = this.ctx.id.toString(), keys = await claimKeys(), now = Date.now();
51
57
  await this.ctx.storage.put({ ends, seen: now, correlation, started: this.started });
52
- await this.ctx.storage.setAlarm(Math.min(ends, now + this.idle));
53
58
  report(correlation, this.started, 'start');
54
59
  this.container.start({ enableInternet: false, env: { ...settings, RER_DEMO: '1', [originVar]: origin, RER_INGRESS_ORIGIN: origin,
55
60
  SESSION_SECRET: random(), SETUP_TOKEN: random(), OWNER_EMAIL: OWNER, RER_OWNER_CLAIM_ISSUER: origin, RER_OWNER_CLAIM_INSTALLATION_ID: id,
56
61
  RER_OWNER_CLAIM_PUBLIC_KEYS: JSON.stringify(keys.publicKeys), RER_DEMO_EXPIRES: endsLocal } });
57
62
  // A container that stops by itself ends the demo too.
58
63
  this.watch();
64
+ await this.ctx.storage.setAlarm(Date.now());
59
65
  await this.healthy(deadline);
60
66
  const token = await signClaim(keys, { origin, installationId: id, email: OWNER, now: Date.now() });
61
67
  const claimed = await boundedFetch(this.port(), 'http://container/auth/owner-claim', { method: 'POST', redirect: 'manual',
@@ -94,17 +100,30 @@ export class DemoContainer extends DurableObject {
94
100
  /** Every request carrying this demo's cookie: proxied while the demo lives, else the ended page. */
95
101
  async fetch(request) {
96
102
  const state = await this.ctx.storage.get(['ends', 'seen']), now = Date.now();
97
- if (!(state.get('ends') > now)) return endedPage(this.env, { status: 410, headers: { 'set-cookie': clearCookie(this.env) } });
103
+ if (!(state.get('ends') > now)) return this.ended();
104
+ if (!this.container.running) return this.gone();
98
105
  if (now - state.get('seen') > 60_000) await this.ctx.storage.put('seen', now);
99
- return this.port().fetch(new Request(inside(new URL(request.url)), request));
106
+ try { return await this.port().fetch(new Request(inside(new URL(request.url)), request)); }
107
+ catch (error) { if (this.container.running && !this.stopped) throw error; return this.gone(); }
108
+ }
109
+
110
+ ended() { return endedPage(this.env, { status: 410, headers: { 'set-cookie': clearCookie(this.env) } }); }
111
+
112
+ /** A container the platform stopped while nothing watched it: end the demo (the alarm retries a failed cleanup). */
113
+ async gone() {
114
+ this.record('exit', { outcome: 'gone' });
115
+ try { await this.end(); } catch (cause) { report(this.correlation, this.started, 'cleanup', { error: category(cause) }); }
116
+ return this.ended();
100
117
  }
101
118
 
102
119
  async alarm() {
103
120
  const state = await this.ctx.storage.get(['ends', 'seen']), now = Date.now();
104
121
  if (await this.ctx.storage.get('stopping')) return this.end();
105
122
  if (!state.get('ends')) return;
106
- if (now >= state.get('ends') || now - state.get('seen') >= this.idle) return this.end();
107
- await this.ctx.storage.setAlarm(Math.min(state.get('ends'), state.get('seen') + this.idle));
123
+ const due = Math.min(state.get('ends'), state.get('seen') + this.idle);
124
+ if (now >= due || !this.container.running) return this.end();
125
+ await new Promise(resolve => { this.wake = resolve; setTimeout(resolve, Math.min(due - now, this.hold)); });
126
+ if (!this.stopped) await this.ctx.storage.setAlarm(Date.now());
108
127
  }
109
128
 
110
129
  /** Destroy the container and delete this demo's state and place; safe to repeat. */
@@ -115,7 +134,7 @@ export class DemoContainer extends DurableObject {
115
134
  }
116
135
 
117
136
  async cleanup() {
118
- this.stopped = true;
137
+ this.stopped = true; this.wake?.();
119
138
  // Keep the alarm and capacity reservation if destruction fails; retry cleanup.
120
139
  await this.ctx.storage.put('stopping', true);
121
140
  await this.ctx.storage.setAlarm(Date.now() + this.cleanupRetry);
@@ -12,28 +12,33 @@ import { siteDeclaration } from '../deploy-kit/site.mjs';
12
12
  export const DEMO_FILES = ['worker.mjs', 'container.mjs', 'capacity.mjs', 'claim.mjs', 'pages.mjs', 'start-script.mjs', 'diagnostics.mjs', 'operator.mjs'];
13
13
  const FRONT_SET = /^(?:RER_.*|SESSION_SECRET|SETUP_TOKEN|OWNER_EMAIL)$/;
14
14
  const SECRET = /SECRET|TOKEN|PASSWORD|_KEY$/;
15
+ // Cloudflare Containers' predefined instance types, smallest first (developers.cloudflare.com/containers/platform-details/limits).
16
+ export const INSTANCE_TYPES = ['lite', 'basic', 'standard-1', 'standard-2', 'standard-3', 'standard-4'];
15
17
 
16
18
  /**
17
19
  * deploy-demo.json: `{ "version": 1, "domain": "run-lamp.com", "name": "Lamp" }`, plus optionally
18
- * `maxInstances` (concurrent demos, default 10) and `settings`, the seed's plain demo settings
19
- * (such as MAIL_PROVIDER: "development"). Settings never carry secrets or what the front sets.
20
+ * `maxInstances` (concurrent demos, default 10), `instanceType` (one of INSTANCE_TYPES, default
21
+ * "basic") and `settings`, the seed's plain demo settings (such as MAIL_PROVIDER: "development").
22
+ * Settings never carry secrets or what the front sets.
20
23
  */
21
24
  export function demoDeclaration(value, originVar) {
22
- assert(value && typeof value === 'object' && !Array.isArray(value) && value.version === 1 && Object.keys(value).every(key => ['version', 'domain', 'name', 'maxInstances', 'settings'].includes(key)), 'invalid-demo-declaration');
25
+ assert(value && typeof value === 'object' && !Array.isArray(value) && value.version === 1 && Object.keys(value).every(key => ['version', 'domain', 'name', 'maxInstances', 'instanceType', 'settings'].includes(key)), 'invalid-demo-declaration');
23
26
  siteDeclaration({ version: 1, domain: value.domain });
24
27
  assert(typeof value.name === 'string' && value.name.trim() === value.name && value.name.length > 0 && value.name.length <= 60 && !/[\p{Cc}\p{Cf}]/u.test(value.name), 'invalid-demo-name');
25
28
  const maxInstances = value.maxInstances ?? 10;
26
29
  assert(Number.isSafeInteger(maxInstances) && maxInstances >= 1 && maxInstances <= 100, 'invalid-demo-max-instances');
30
+ const instanceType = value.instanceType ?? 'basic';
31
+ assert(INSTANCE_TYPES.includes(instanceType), 'invalid-demo-instance-type');
27
32
  const settings = value.settings ?? {};
28
33
  assert(settings && typeof settings === 'object' && !Array.isArray(settings) && Object.entries(settings).every(([name, setting]) =>
29
34
  /^[A-Z][A-Z0-9_]{0,63}$/.test(name) && !FRONT_SET.test(name) && !SECRET.test(name) && name !== originVar && typeof setting === 'string' && setting.length <= 1024), 'invalid-demo-settings');
30
- return { domain: value.domain, name: value.name, maxInstances, settings };
35
+ return { domain: value.domain, name: value.name, maxInstances, instanceType, settings };
31
36
  }
32
37
 
33
38
  /** The demo Worker's name and its Wrangler configuration; no provider request. */
34
39
  export function demoPlan({ project, environment, compatibilityDate, originVar, declaration, turnstileSiteKey }) {
35
40
  assert(/^\d{4}-\d{2}-\d{2}$/.test(compatibilityDate ?? '') && /^[A-Z][A-Z0-9_]{0,63}$/.test(originVar ?? ''), 'invalid-plan');
36
- const { domain, name, maxInstances, settings } = demoDeclaration(declaration, originVar);
41
+ const { domain, name, maxInstances, instanceType, settings } = demoDeclaration(declaration, originVar);
37
42
  const worker = `${ownerWorkerName(project, environment)}--demo`, hostname = `demo.${domain}`, container = worker.replace(/-+/g, '-');
38
43
  assert(resourceName(worker), 'owner-name-too-long');
39
44
  // Rate limit namespaces are account-wide integers: one per demo Worker.
@@ -46,10 +51,10 @@ export function demoPlan({ project, environment, compatibilityDate, originVar, d
46
51
  ...(turnstileSiteKey ? { TURNSTILE_SITE_KEY: turnstileSiteKey } : {}) },
47
52
  durable_objects: { bindings: [{ name: 'DEMO', class_name: 'DemoContainer' }, { name: 'CAPACITY', class_name: 'DemoCapacity' }] },
48
53
  migrations: [{ tag: 'v1', new_sqlite_classes: ['DemoContainer', 'DemoCapacity'] }],
49
- containers: [{ name: container, class_name: 'DemoContainer', image: './image/Dockerfile', max_instances: maxInstances, instance_type: 'basic' }],
54
+ containers: [{ name: container, class_name: 'DemoContainer', image: './image/Dockerfile', max_instances: maxInstances, instance_type: instanceType }],
50
55
  ratelimits: [{ name: 'STARTS', namespace_id: namespace, simple: { limit: 3, period: 60 } }],
51
56
  };
52
- return { worker, hostname, container, record: demoRecord({ worker, hostname, container }), origin: `https://${hostname}`, maxInstances, settings: Object.keys(settings), wrangler };
57
+ return { worker, hostname, container, record: demoRecord({ worker, hostname, container }), origin: `https://${hostname}`, maxInstances, instanceType, settings: Object.keys(settings), wrangler };
53
58
  }
54
59
 
55
60
  /** The demo's record of what `rer deploy --demo` creates, kept on the provider so a
@@ -1,3 +1,5 @@
1
+ import { readinessWindow, readinessAPI } from './readiness-window.mjs';
2
+ import { uploadedWorker } from './uploaded-worker.mjs';
1
3
  import { recordDeployFailure } from './diagnostics.mjs';
2
4
  import { verifyServiceGrants } from './service-grants.mjs';
3
5
  import { assert, hash, validatePlan } from './validation.mjs';
@@ -42,8 +44,11 @@ export async function deploy({api,plan,artifact,artifactSha256,previousReceipt,r
42
44
  const migrations = [];
43
45
  // A migration failure names its database, so the owner knows which one to inspect.
44
46
  for (const item of plan.d1) migrations.push({binding:item.binding,...await migrate(api,resources.d1.find(x => x.binding === item.binding).id,item.migrations,{apply:!unchanged,upgrade:true}).catch(error => { error.resource ??= `d1:${item.name}`; throw error; })});
45
- if (!unchanged) await uploadWorker(api,{plan,artifact,bindings,secrets,migration,fingerprint});
46
- const published = unchanged ? existing : await activeWorker(api,plan.worker); assert(published,'missing-deployed-worker');
47
+ const window = readiness.window ?? readinessWindow({...(healthOptions.now ? {clock:healthOptions.now} : {}), ...(healthOptions.sleep ? {sleep:healthOptions.sleep} : {}), ...readiness});
48
+ let upload;
49
+ if (!unchanged) { window.start(); upload = await uploadWorker(api,{plan,artifact,bindings,secrets,migration,fingerprint}); }
50
+ if (!unchanged) api = readinessAPI(api, window);
51
+ const published = unchanged ? existing : await uploadedWorker({api,worker:plan.worker,upload,previous:existing,fingerprint,window}); assert(published,'missing-deployed-worker');
47
52
  verifyBindings(published.settings.bindings,bindings);
48
53
  verifyScheduledHandler(published,plan);
49
54
  // Finish routing activation before applying schedules to this deployment.
@@ -61,7 +66,7 @@ export async function deploy({api,plan,artifact,artifactSha256,previousReceipt,r
61
66
  const asset = publicAssetPaths(artifact.assets.map(x => x.path))[0];
62
67
  try {
63
68
  if (unchanged) await verifyHealth({...healthOptions,api,plan,receipt,fetch,asset});
64
- else await firstHealth({api,plan,receipt,fetch,healthOptions,readiness,onHealth,asset});
69
+ else await firstHealth({api,plan,receipt,fetch,healthOptions,readiness:{...readiness,window,freshUpload:!existing},onHealth,asset});
65
70
  } catch (error) { throw recordDeployFailure(error,{step:'health',...(error.code ? {code:error.code,output:error.message} : {})}); }
66
71
  return receipt;
67
72
  }