@runeditrun/rer 0.2.84 → 0.2.85

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/README.md +21 -24
  2. package/cli/README.md +17 -1
  3. package/cli/bounded.mjs +1 -1
  4. package/cli/business/carry.mjs +149 -0
  5. package/cli/business/command.mjs +6 -1
  6. package/cli/business/connect.mjs +1 -1
  7. package/cli/business/local-commands.mjs +2 -0
  8. package/cli/business/opt-ins.mjs +8 -4
  9. package/cli/business/questions.mjs +4 -1
  10. package/cli/business/state.mjs +1 -1
  11. package/cli/business/supervisor.mjs +7 -1
  12. package/cli/container-transfer.mjs +2 -2
  13. package/cli/contract.mjs +6 -6
  14. package/cli/demo-native.mjs +2 -1
  15. package/cli/deploy-command.mjs +6 -4
  16. package/cli/deploy.mjs +9 -7
  17. package/cli/errors.mjs +1 -1
  18. package/cli/export.mjs +1 -1
  19. package/cli/human-error.mjs +20 -0
  20. package/cli/lifecycle.mjs +23 -5
  21. package/cli/main.mjs +1 -1
  22. package/cli/managed-data-schema.mjs +114 -0
  23. package/cli/managed-data-zip.mjs +116 -0
  24. package/cli/managed-data.mjs +110 -0
  25. package/cli/managed-server.mjs +25 -14
  26. package/cli/native-owner-entry.mjs +86 -0
  27. package/cli/output.mjs +3 -2
  28. package/cli/parse.mjs +2 -2
  29. package/cli/portability-empty.mjs +59 -0
  30. package/cli/portability-migrations.mjs +7 -5
  31. package/cli/portability-policy.mjs +5 -2
  32. package/cli/portability-worker.mjs +15 -6
  33. package/cli/portability.mjs +30 -8
  34. package/cli/ready-summary.mjs +9 -0
  35. package/cli/run-transfers.mjs +37 -0
  36. package/cli/runtime-front-door.mjs +4 -4
  37. package/cli/server-proxy.mjs +4 -3
  38. package/cli/server-registry.mjs +13 -8
  39. package/cli/site.mjs +6 -1
  40. package/cli/transfers.mjs +17 -4
  41. package/edition-authoring/base-copies.mjs +55 -7
  42. package/foundation/runtime/contract-docs.mjs +3 -2
  43. package/foundation/runtime/run-data.d.mts +1 -0
  44. package/foundation/runtime/run-data.mjs +2 -0
  45. package/global/CHANGELOG.md +33 -0
  46. package/global/README.md +21 -24
  47. package/global/cli/command.mjs +8 -2
  48. package/global/cli/install.mjs +4 -5
  49. package/global/cli/path-link.mjs +3 -2
  50. package/global/cli/repo-command.mjs +3 -7
  51. package/global/launch/dev.mjs +12 -2
  52. package/global/launch/facts.mjs +2 -2
  53. package/global/launch/render.mjs +16 -9
  54. package/global/launch/state.mjs +4 -4
  55. package/global/main.mjs +12 -7
  56. package/install.sh +17 -6
  57. package/modules/container/README.md +6 -1
  58. package/modules/container/adapters/d1-limits.mjs +286 -0
  59. package/modules/container/adapters/d1-sqlite.mjs +95 -0
  60. package/modules/container/adapters/d1-workerd-preload.mjs +19 -0
  61. package/modules/container/adapters/d1-workerd-setup.mjs +26 -0
  62. package/modules/container/adapters/d1-workerd.mjs +5 -0
  63. package/modules/container/adapters/sqlite-worker.mjs +5 -3
  64. package/modules/container/build.mjs +1 -0
  65. package/modules/container/image-variables.mjs +8 -3
  66. package/modules/container/transfer.mjs +14 -4
  67. package/modules/container/worker-engine.mjs +3 -3
  68. package/modules/demo-host/build.mjs +1 -0
  69. package/modules/demo-host/native/prepare.mjs +2 -1
  70. package/modules/demo-host/native/sql.mjs +7 -2
  71. package/modules/deploy-kit/README.md +22 -2
  72. package/modules/deploy-kit/d1-import-diagnostics.mjs +56 -0
  73. package/modules/deploy-kit/d1-import.mjs +17 -5
  74. package/modules/deploy-kit/diagnostics.mjs +29 -3
  75. package/modules/deploy-kit/owner-cli.mjs +20 -7
  76. package/modules/deploy-kit/provider-transport.mjs +19 -4
  77. package/modules/deploy-kit/provider.mjs +57 -22
  78. package/modules/deploy-kit/readiness-window.mjs +1 -1
  79. package/modules/deploy-kit/site.mjs +8 -3
  80. package/modules/deploy-kit/worker.mjs +4 -4
  81. package/modules/import-kit/src/d1/README.md +23 -4
  82. package/modules/import-kit/src/d1/atomic-prefix.ts +2 -2
  83. package/modules/import-kit/src/d1/budget.ts +15 -7
  84. package/modules/import-kit/src/d1/column-layout.ts +5 -0
  85. package/modules/import-kit/src/d1/creation.ts +15 -8
  86. package/modules/import-kit/src/d1/database.ts +3 -3
  87. package/modules/import-kit/src/d1/erasure-pages.ts +2 -1
  88. package/modules/import-kit/src/d1/erasure.ts +2 -2
  89. package/modules/import-kit/src/d1/jobs.ts +10 -6
  90. package/modules/import-kit/src/d1/plans.ts +14 -8
  91. package/modules/import-kit/src/d1/retirement.ts +2 -2
  92. package/modules/import-kit/src/d1/sets.ts +1 -3
  93. package/modules/import-kit/src/d1/staged-creation.ts +3 -3
  94. package/modules/import-kit/src/door/limits.ts +1 -1
  95. package/modules/import-kit/src/door/refusals.ts +1 -1
  96. package/modules/portability/README.md +112 -4
  97. package/modules/portability/backfills.mjs +9 -8
  98. package/modules/portability/bridge.mjs +12 -5
  99. package/modules/portability/catalogue.mjs +12 -5
  100. package/modules/portability/files.mjs +4 -3
  101. package/modules/portability/http.mjs +3 -3
  102. package/modules/portability/import.mjs +18 -9
  103. package/modules/portability/index.d.mts +4 -3
  104. package/modules/portability/index.mjs +1 -1
  105. package/modules/portability/ledgers.mjs +3 -2
  106. package/modules/portability/legacy-safety.mjs +11 -2
  107. package/modules/portability/migration-history.mjs +2 -2
  108. package/modules/portability/progress.mjs +1 -0
  109. package/modules/portability/restore-empty.mjs +12 -0
  110. package/modules/release/github-verify.mjs +11 -2
  111. package/onboarding/adapter.mjs +35 -6
  112. package/onboarding/app-fetch.mjs +6 -4
  113. package/onboarding/development-runtime.mjs +19 -0
  114. package/onboarding/local/operation.mjs +45 -27
  115. package/onboarding/loopback-fetch.mjs +16 -0
  116. package/onboarding/operator-installer.mjs +2 -4
  117. package/onboarding/process-diagnostics.mjs +6 -2
  118. package/onboarding/production-runtime.mjs +4 -2
  119. package/onboarding/readiness.mjs +1 -0
  120. package/package.json +1 -1
  121. package/scripts/publish-check/public_hygiene.py +1 -1
@@ -11,7 +11,7 @@ import { dependencyEnvironment } from './dependency-environment.mjs';
11
11
  import { labels } from './adapter-labels.mjs';
12
12
  import { chooseOrigin, prepareSettings, readSettings } from './adapter-settings.mjs';
13
13
  import {listenerPorts,listenerOwnership,inspectionContext} from './process-diagnostics.mjs';
14
- import { appFetch } from './app-fetch.mjs';
14
+ import { appFetch, loopbackRequest } from './app-fetch.mjs';
15
15
  import { owner, signIn } from './adapter-auth.mjs';
16
16
  import { installerDevKey } from './dev-identity.mjs';
17
17
  import { assertArchiveFree } from './archive-output.mjs';
@@ -208,26 +208,55 @@ async function start(context, hooks) {
208
208
  const { store, onApp, signal } = context;
209
209
  await store.step(labels.start);
210
210
  const [[command, args = [], options = {}]] = await commandsFor(context, hooks.start);
211
- const { health = '/health', ready, timeoutMs, softAfterMs, intervalMs, ...spawnOptions } = options;
211
+ const { health = '/health', ready, timeoutMs, softAfterMs, intervalMs, runtimePortHandshake, ...spawnOptions } = options;
212
212
  if (hooks.guard) await hooks.guard(context);
213
213
  let child;
214
214
  try { child = store.spawn(labels.start, command, args, { cwd: context.root, signal, ...spawnOptions }); } catch (error) {
215
215
  if (signal?.aborted) throw error;
216
216
  throw installationFailure('command_failed', { step: 'start', diagnostic: error });
217
217
  }
218
+ let announcement,detectedMismatch;
219
+ const mismatch=port=>({fatal:detectedMismatch=`the application listened on port ${port} but the CLI expected ${expectedPort}`});
220
+ const announced=message=>{if(message?.type==='rer-listening')announcement=message;};
221
+ if(runtimePortHandshake)child.on('message',announced);
218
222
  context.app = child;
219
223
  await onApp(child);
220
224
  const url = new URL(health, context.origin).href;
221
- const expectedPort=context.runtimePort??Number(new URL(context.origin).port||80);
222
- const readinessLabel=`${labels.start} (expected internal port ${expectedPort})`;
225
+ let expectedPort=context.runtimePort??Number(new URL(context.origin).port||80);
226
+ const readinessLabel=runtimePortHandshake?`${labels.start} (waiting for the bound internal listener)`:`${labels.start} (expected internal port ${expectedPort})`;
223
227
  const ownedPorts=async()=>{
224
228
  try{return await listenerPorts(child.pid);}
225
229
  catch(error){throw installationFailure('command_failed',{step:'start',diagnostic:error});}
226
230
  };
227
231
  try {
228
- await store.waitForReady(readinessLabel, child, ready ? probeSignal => ready(url, probeSignal, context) : probeSignal => (hooks.health ?? defaultHealth)(url, probeSignal, context), { signal, timeoutMs: ['dev','preview'].includes(context.verb)?Math.min(timeoutMs??60000,120000):(timeoutMs??900000), ...(softAfterMs ? { softAfterMs } : {}), ...(intervalMs ? { intervalMs } : {}) });
232
+ await store.waitForReady(readinessLabel, child, async probeSignal => {
233
+ if(runtimePortHandshake){
234
+ if(!announcement)return {ready:false,message:'Waiting for the application listener handshake'};
235
+ const {port,requestedPort}=announcement;
236
+ if(!Number.isInteger(port)||port<1||port>65535)return {fatal:'The application reported an invalid listener port.'};
237
+ if(requestedPort!==0)return mismatch(port);
238
+ if(context.runtimePort!==port){
239
+ const ownership=await listenerOwnership(child.pid,port,'127.0.0.1',inspectionContext({port,signal:probeSignal,budgetMs:3000}));
240
+ if(ownership.status!=='owned')return {fatal:'The application listener handshake did not identify an owned socket.'};
241
+ context.setRuntimePort(port);context.runtimePort=port;expectedPort=port;
242
+ }
243
+ }
244
+ const result=await (ready??hooks.health??defaultHealth)(url,probeSignal,context);
245
+ if(result===true||result?.ready===true)return result;
246
+ // Auxiliary runtime listeners are common. Only an owned listener serving the
247
+ // application's healthy response proves a mismatched application port.
248
+ const ports=await listenerPorts(child.pid,inspectionContext({signal:probeSignal,budgetMs:3000}));
249
+ if(!ports.includes(expectedPort))for(const port of ports){
250
+ try{
251
+ const reply=await loopbackRequest({port,path:health,headers:{host:new URL(url).host},signal:probeSignal,timeoutMs:1000});
252
+ if(reply.status===200&&JSON.parse(reply.body.toString()).status==='ok')return mismatch(port);
253
+ }catch(error){if(probeSignal.aborted)throw error;}
254
+ }
255
+ return result;
256
+ }, { signal, timeoutMs: Math.min(timeoutMs??60000,60000), ...(softAfterMs ? { softAfterMs } : {}), ...(intervalMs ? { intervalMs } : {}) });
229
257
  } catch (error) {
230
258
  if (signal?.aborted) throw error;
259
+ if(detectedMismatch)throw installationFailure('command_failed',{step:'start',diagnostic:error});
231
260
  const ports=await ownedPorts();
232
261
  if(ports.length){
233
262
  let diagnosis;
@@ -237,7 +266,7 @@ async function start(context, hooks) {
237
266
  store.report(message);const prior=approvedFailure(error);error=commandFailure(`${prior?.message??readinessLabel}\n${message}`,prior??{});
238
267
  }
239
268
  throw installationFailure('command_failed', { step: 'start', diagnostic: error });
240
- }
269
+ } finally { if(runtimePortHandshake)child.removeListener('message',announced); }
241
270
  // Another app can take the loopback port between the port check and the bind;
242
271
  // its /health would pass. Claim and sign in only against the process this
243
272
  // setup started.
@@ -1,5 +1,5 @@
1
1
  // Requests rer itself makes to a local app's own origin (health, sign-in,
2
- // dev identity). A directly served origin uses fetch. A front-door
2
+ // dev identity). Direct loopback fetches close each connection. A front-door
3
3
  // origin (http://NAME.localhost:PORT) is never resolved and never goes through
4
4
  // the door: rer connects with node:http to that checkout's own proxy on
5
5
  // 127.0.0.1, which keeps the Host header (fetch drops a Host override, and musl
@@ -10,6 +10,7 @@
10
10
  // whatever answers that name (the door, or a process that took its port) never
11
11
  // receives rer's own requests, which can carry the checkout's dev key.
12
12
  import http from 'node:http';
13
+ import { loopbackFetch } from './loopback-fetch.mjs';
13
14
  import { basename, dirname } from 'node:path';
14
15
  import { fileURLToPath } from 'node:url';
15
16
  // The shared loopback predicate, beside this copy in Base or in a seed's scripts/.
@@ -32,7 +33,8 @@ export function loopbackRequest({ host = '127.0.0.1', port, path = '/', method =
32
33
  response.on('end', () => resolve({ status: response.statusCode, statusText: response.statusMessage ?? '', rawHeaders: response.rawHeaders, body: Buffer.concat(chunks) }));
33
34
  response.on('error', reject);
34
35
  });
35
- request.setTimeout(timeoutMs, () => request.destroy(Object.assign(Error(`No answer from ${host}:${port} within ${timeoutMs / 1000} s.`), { code: 'ETIMEDOUT' })));
36
+ const timer=setTimeout(() => request.destroy(Object.assign(Error(`No answer from ${host}:${port} within ${timeoutMs / 1000} s.`), { code: 'ETIMEDOUT' })),timeoutMs);
37
+ request.once('close',()=>clearTimeout(timer));
36
38
  request.on('error', reject);
37
39
  request.end(body);
38
40
  });
@@ -53,14 +55,14 @@ function unrouted(url) {
53
55
  export async function appFetch(input, init = {}) {
54
56
  let url = new URL(input instanceof Request ? input.url : String(input));
55
57
  if (!routes.has(url.origin) && isLocalhostName(url.hostname)) throw unrouted(url);
56
- if (!routes.has(url.origin)) return fetch(input, init);
58
+ if (!routes.has(url.origin)) return loopbackFetch(input, init);
57
59
  let method = (init.method ?? 'GET').toUpperCase(), body = await bodyBytes(init.body);
58
60
  const sent = Object.fromEntries(new Headers(init.headers ?? {}));
59
61
  if (body !== undefined && init.body instanceof URLSearchParams && !sent['content-type']) sent['content-type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
60
62
  for (let hops = 0; ; hops++) {
61
63
  const route = routes.get(url.origin);
62
64
  if (!route && isLocalhostName(url.hostname)) throw unrouted(url);
63
- if (!route) return fetch(url, { ...init, method, body });
65
+ if (!route) return loopbackFetch(url, { ...init, method, body });
64
66
  const reply = await loopbackRequest({ port: route.port, path: url.pathname + url.search, method, headers: { ...sent, ...route.headers, host: url.host, ...(body ? { 'content-length': String(body.length) } : {}) }, body, signal: init.signal });
65
67
  const headers = new Headers();
66
68
  for (let i = 0; i < reply.rawHeaders.length; i += 2) headers.append(reply.rawHeaders[i], reply.rawHeaders[i + 1]);
@@ -0,0 +1,19 @@
1
+ import {createRequire} from 'node:module';
2
+ import {join} from 'node:path';
3
+ import {pathToFileURL} from 'node:url';
4
+
5
+ // Bind first, then announce the actual application listener over the private
6
+ // parent channel. No free-port probe is released before Vite binds.
7
+ const require=createRequire(join(process.cwd(),'package.json'));
8
+ const {createServer}=await import(pathToFileURL(require.resolve('vite')).href);
9
+ const args=process.argv.slice(2),port=Number(args[args.indexOf('--port')+1]);
10
+ const server=await createServer({server:{host:'127.0.0.1',port,strictPort:true}});
11
+ let stopping;
12
+ const stop=()=>stopping??=server.close().finally(()=>{if(process.connected)process.disconnect();});
13
+ process.on('SIGINT',()=>void stop());process.on('SIGTERM',()=>void stop());
14
+ try {
15
+ await server.listen();
16
+ const actual=server.httpServer.address().port;
17
+ process.send?.({type:'rer-listening',requestedPort:port,port:actual});
18
+ server.printUrls();
19
+ }catch(error){await stop();throw error;}
@@ -47,7 +47,12 @@ export async function localOperation(root, inheritedToken) {
47
47
  try { await file.writeFile(JSON.stringify({ ...self, token })) } finally { await file.close() }
48
48
  const acquired = await identity(path)
49
49
  return { token, release: async () => {
50
- if (await identity(path) === acquired) await unlink(path).catch(missing)
50
+ let owner
51
+ try { owner = JSON.parse(await readFile(path, 'utf8')) } catch (error) {
52
+ if (error.code === 'ENOENT') return
53
+ throw error
54
+ }
55
+ if (owner.token === token && await identity(path) === acquired) await unlink(path).catch(missing)
51
56
  } }
52
57
  }
53
58
 
@@ -70,30 +75,36 @@ export async function ownerAlive(owner) {
70
75
  // just created. Every starter that judged the same stale file competes for one
71
76
  // exclusive guard named after that file's identity; only the guard holder may
72
77
  // remove it, and only while the path still names that exact file. A new lock
73
- // has a new identity, so it can never be removed as stale.
78
+ // has a new identity. Keep the judged descriptor open through the takeover:
79
+ // otherwise its deleted inode can be reused by a new lock while a delayed
80
+ // contender still holds the old identity. Filesystem timestamps do not make
81
+ // inode reuse an exclusive ownership primitive.
74
82
  async function takeOver(path) {
75
- const judged = await staleIdentity(path)
76
- if (judged === undefined) return false
77
- if (judged === null) return true // Already gone: retry the exclusive create.
78
- const guardPath = `${path}.takeover-${judged}`
79
- let guard
80
- for (let attempt = 0; !guard; attempt++) {
81
- try { guard = await open(guardPath, 'wx', 0o600) } catch (error) {
82
- if (error.code !== 'EEXIST') throw error
83
- // Another starter is taking over; it, or a faster starter, owns the lock.
84
- // A guard whose owner was killed is removed once, after its grace.
85
- if (attempt > 0 || !await removeAbandonedGuard(guardPath, path)) return false
86
- }
87
- }
83
+ const stale = await staleIdentity(path)
84
+ if (stale === undefined) return false
85
+ if (stale === null) return true // Already gone: retry the exclusive create.
86
+ const { handle, id: judged } = stale
88
87
  try {
89
- await guard.writeFile(JSON.stringify(await currentProcess()))
90
- const current = await identity(path)
91
- if (current === judged) await unlink(path).catch(missing)
92
- return true
93
- } finally {
94
- await guard.close()
95
- await unlink(guardPath).catch(missing)
96
- }
88
+ const guardPath = `${path}.takeover-${judged}`
89
+ let guard
90
+ for (let attempt = 0; !guard; attempt++) {
91
+ try { guard = await open(guardPath, 'wx', 0o600) } catch (error) {
92
+ if (error.code !== 'EEXIST') throw error
93
+ // Another starter is taking over; it, or a faster starter, owns the lock.
94
+ // A guard whose owner was killed is removed once, after its grace.
95
+ if (attempt > 0 || !await removeAbandonedGuard(guardPath, path)) return false
96
+ }
97
+ }
98
+ try {
99
+ await guard.writeFile(JSON.stringify(await currentProcess()))
100
+ const current = await identity(path)
101
+ if (current === judged) await unlink(path).catch(missing)
102
+ return true
103
+ } finally {
104
+ await guard.close()
105
+ await unlink(guardPath).catch(missing)
106
+ }
107
+ } finally { await handle.close() }
97
108
  }
98
109
 
99
110
  // Returns the identity of a stale lock, null when the lock is already gone, or
@@ -105,15 +116,22 @@ async function staleIdentity(path) {
105
116
  if (error.code === 'ENOENT') return null
106
117
  throw error
107
118
  }
119
+ let retained = false
108
120
  try {
109
121
  const status = await handle.stat({ bigint: true })
110
122
  const id = key(status)
111
123
  try {
112
124
  const owner = JSON.parse(await handle.readFile('utf8'))
113
- if (Number.isSafeInteger(owner.pid) && owner.pid > 0) return await ownerAlive(owner) ? undefined : id
125
+ if (Number.isSafeInteger(owner.pid) && owner.pid > 0) {
126
+ if (await ownerAlive(owner)) return undefined
127
+ retained = true
128
+ return { handle, id }
129
+ }
114
130
  } catch { /* Half-written or unreadable: judged by age below. */ }
115
- return Date.now() - Number(status.mtimeMs) > graceMs ? id : undefined
116
- } finally { await handle.close() }
131
+ if (Date.now() - Number(status.mtimeMs) <= graceMs) return undefined
132
+ retained = true
133
+ return { handle, id }
134
+ } finally { if (!retained) await handle.close() }
117
135
  }
118
136
 
119
137
  // A takeover guard left by a killed starter would otherwise block every later
@@ -162,7 +180,7 @@ async function identity(path) {
162
180
  }
163
181
  }
164
182
 
165
- // Inode numbers can be reused after deletion; the change time cannot repeat.
183
+ // Compare metadata while the judged inode remains pinned by its descriptor.
166
184
  const key = (status) => `${status.dev}-${status.ino}-${status.ctimeNs}`
167
185
  // A rename changes ctime, so a moved file is matched by its unchanged fields.
168
186
  const movedKey = (status) => `${status.dev}-${status.ino}-${status.birthtimeNs}-${status.mtimeNs}`
@@ -0,0 +1,16 @@
1
+ import { basename, dirname } from 'node:path';
2
+ import { fileURLToPath } from 'node:url';
3
+
4
+ const portable = basename(dirname(fileURLToPath(import.meta.url))) === 'base-onboarding';
5
+ const { isLoopbackHost } = await import(new URL(portable ? '../base-cli/modules/operator-auth/loopback.mjs' : '../modules/operator-auth/loopback.mjs', import.meta.url));
6
+
7
+ // Local harness servers may close idle sockets between readiness and a claim.
8
+ // Close each exchange instead of pooling a socket that can already be closed;
9
+ // never retry a request, particularly a POST with effects.
10
+ export function loopbackFetch(input, init = {}) {
11
+ const url = new URL(input instanceof Request ? input.url : String(input));
12
+ if (!['http:', 'https:'].includes(url.protocol) || !isLoopbackHost(url.hostname)) return fetch(input, init);
13
+ const headers = new Headers(init.headers ?? (input instanceof Request ? input.headers : undefined));
14
+ headers.set('connection', 'close');
15
+ return fetch(input, { ...init, headers });
16
+ }
@@ -5,7 +5,6 @@ import { selectLocalState, LocalStateSafetyError } from './local/state.mjs';
5
5
  import {operatorPrerequisites} from './operator-prerequisites.mjs';
6
6
  import { migrateOperator } from './operator-migrations.mjs';
7
7
  import { installOperator } from './operator-install.mjs';
8
- import { projectViteBinary } from './project-vite.mjs';
9
8
  import { join, delimiter } from 'node:path';
10
9
 
11
10
  export function operatorInstaller({ database, features, prepare, prepareData }) {
@@ -35,11 +34,10 @@ export function operatorInstaller({ database, features, prepare, prepareData })
35
34
  // No runtime rer starts serves the Local Explorer: it reads and writes the store
36
35
  // without the key. trafficProxy also refuses /cdn-cgi/* on the public listener.
37
36
  const devBindings = devKey => devKey ? { RER_DEV_KEY: devKey, RER_DEV_IDENTITY: 'on' } : {};
38
- const internalPort = port => { if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('A local runtime requires the traffic proxy internal port.'); return String(port); };
39
37
  const developmentEnvironment = () => { const { RER_MODELS_SERVICE, RER_MODELS_KEY, RER_DEMO, RER_DEMO_EXPIRES, RER_STATE_DIR, RER_DEMO_RUN_URL, ...env } = process.env; return env; };
40
38
  // A demo's Vite persists to its own folder (the seed's vite.config reads RER_STATE_DIR)
41
39
  // and its Worker sees RER_DEMO=1 and the demo's end (modules/demo).
42
40
  const demoBindings = demo => demo ? { RER_DEMO: '1', RER_DEMO_EXPIRES: demo.ends, RER_STATE_DIR: demo.state, RER_DEMO_RUN_URL: demo.runUrl } : {};
43
- export const developmentTarget = ({ root, origin, runtimePort, devKey, modelsLive, demo }) => [process.execPath, [projectViteBinary(root), 'dev', '--host', '127.0.0.1', '--port', internalPort(runtimePort), '--strictPort'], { env: { ...developmentEnvironment(), PATH: [process.env.PATH, join(root, 'node_modules', '.bin')].filter(value => value !== undefined).join(delimiter), RER_DEV_ORIGIN: origin, WRANGLER_SEND_METRICS: 'false', X_LOCAL_EXPLORER: 'false', ...devBindings(devKey), ...(modelsLive ? { RER_MODELS_SERVICE: modelsLive.baseUrl, RER_MODELS_KEY: modelsLive.apiKey } : {}), ...demoBindings(demo) } }];
41
+ export const developmentTarget = ({ root, origin, devKey, modelsLive, demo }) => [process.execPath, [fileURLToPath(new URL('./development-runtime.mjs',import.meta.url)), 'dev', '--host', '127.0.0.1', '--port', '0', '--strictPort'], { runtimePortHandshake: true, stdio: ['ignore','pipe','pipe','ipc'], env: { ...developmentEnvironment(), PATH: [process.env.PATH, join(root, 'node_modules', '.bin')].filter(value => value !== undefined).join(delimiter), RER_DEV_ORIGIN: origin, WRANGLER_SEND_METRICS: 'false', X_LOCAL_EXPLORER: 'false', ...devBindings(devKey), ...(modelsLive ? { RER_MODELS_SERVICE: modelsLive.baseUrl, RER_MODELS_KEY: modelsLive.apiKey } : {}), ...demoBindings(demo) } }];
44
42
 
45
- export const previewTarget = ({ origin, runtimePort, devKey, scheduled }) => [process.execPath, [fileURLToPath(new URL('./production-runtime.mjs', import.meta.url))], { env: { ...process.env, RER_DEV_ORIGIN: origin, RER_RUNTIME_HOST: '127.0.0.1', RER_RUNTIME_PORT: internalPort(runtimePort), WRANGLER_SEND_METRICS: 'false', CLOUDFLARE_INCLUDE_PROCESS_ENV: 'false', X_LOCAL_EXPLORER: 'false', RER_RUNTIME_TRIGGERS: scheduled ? '1' : '0', ...(devKey ? { RER_DEV_KEY: devKey } : {}) } }];
43
+ export const previewTarget = ({ origin, devKey, scheduled }) => [process.execPath, [fileURLToPath(new URL('./production-runtime.mjs', import.meta.url))], { runtimePortHandshake: true, stdio: ['ignore','pipe','pipe','ipc'], env: { ...process.env, RER_DEV_ORIGIN: origin, RER_RUNTIME_HOST: '127.0.0.1', RER_RUNTIME_PORT: '0', WRANGLER_SEND_METRICS: 'false', CLOUDFLARE_INCLUDE_PROCESS_ENV: 'false', X_LOCAL_EXPLORER: 'false', RER_RUNTIME_TRIGGERS: scheduled ? '1' : '0', ...(devKey ? { RER_DEV_KEY: devKey } : {}) } }];
@@ -158,9 +158,13 @@ async function descendants(pid,context){
158
158
  const owned=new Set([pid]);for(let changed=true;changed;){changed=false;for(const [child,parent]of rows)if(owned.has(parent)&&!owned.has(child)){owned.add(child);changed=true;}}
159
159
  return owned;
160
160
  }
161
+ // The process's own listeners first, then its descendants', each in port order:
162
+ // a runtime's own application listener comes before the helper sockets its
163
+ // children open (Miniflare's workerd also answers the application's health).
161
164
  export async function listenerPorts(pid,context=inspectionContext()){
162
- const owned=await descendants(pid,context);
163
- return [...new Set((await listeners([...owned],context)).filter(row=>owned.has(row.pid)).flatMap(row=>row.names.map(portOf)).filter(port=>Number.isInteger(port)&&port>0&&port<=65535))].sort((a,b)=>a-b);
165
+ const owned=await descendants(pid,context),rows=(await listeners([...owned],context)).filter(row=>owned.has(row.pid));
166
+ const ports=group=>group.flatMap(row=>row.names.map(portOf)).filter(port=>Number.isInteger(port)&&port>0&&port<=65535).sort((a,b)=>a-b);
167
+ return [...new Set([...ports(rows.filter(row=>row.pid===pid)),...ports(rows.filter(row=>row.pid!==pid))])];
164
168
  }
165
169
  // An exact health address can use positive own-tree evidence. localhost can
166
170
  // reach either loopback family, so it also needs a completed inspection with
@@ -9,7 +9,7 @@ import {watchProductionAssets} from './production-assets.mjs';
9
9
  // only the pinned Miniflare, which owns one workerd and no bundler or
10
10
  // source/config watcher. Built-asset changes refresh its manifest.
11
11
  let planner,stopping,runtime,closeAssets;
12
- const stop=()=>stopping??=(async()=>{planner?.kill('SIGTERM');await closeAssets?.();await runtime?.dispose();})();
12
+ const stop=()=>stopping??=(async()=>{planner?.kill('SIGTERM');await closeAssets?.();await runtime?.dispose();if(process.connected)process.disconnect();})();
13
13
  process.on('SIGINT',()=>void stop());process.on('SIGTERM',()=>void stop());
14
14
  async function plan(){
15
15
  let text='';
@@ -27,7 +27,9 @@ try{
27
27
  runtime=new Miniflare({...convertV4MiniflareOptions(options),resourcePersistencePath:resolve(process.cwd(),'.wrangler/state/v3')});
28
28
  if(stopping)await runtime.dispose();
29
29
  else {
30
- await runtime.ready;
30
+ const address=await runtime.ready;
31
+ process.send?.({type:'rer-listening',requestedPort:options.port,port:Number(address.port)});
32
+ options.port=Number(address.port);
31
33
  if (!stopping) closeAssets=watchProductionAssets(runtime,options,value=>({...convertV4MiniflareOptions(value),resourcePersistencePath:resolve(process.cwd(),'.wrangler/state/v3')}),error=>{process.stderr.write(`Preview asset refresh failed: ${error.message}\n`);process.exitCode=1;void stop();});
32
34
  }
33
35
  }
@@ -48,6 +48,7 @@ export async function waitForReadiness(label, child, health, options, capture, r
48
48
  if(stopped())return await drain();
49
49
  if(signal?.aborted)return await fail('cancel');
50
50
  if(now()-start>=timeoutMs)return await fail('deadline');
51
+ if(typeof result.value?.fatal==='string')throw failure(result.value.fatal,{reason:'mismatch'});
51
52
  if(result.value===true||result.value?.ready===true)return result.value;
52
53
  if(typeof result.value==='string')lastHealth=result.value;
53
54
  else if(typeof result.value?.message==='string')lastHealth=result.value.message;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runeditrun/rer",
3
- "version": "0.2.84",
3
+ "version": "0.2.85",
4
4
  "description": "The rer command: install, set up, run and launch Run Edit Run checkouts.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -18,7 +18,7 @@ SCHEME_CHARACTERS = frozenset('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVW
18
18
  # acquire trailer privileges. Only the address span is omitted from email checks.
19
19
  COAUTHOR = re.compile(
20
20
  rb'^Co-Authored-By:[ \t]+(?=[^ \t])[^<>\r\n]*[^<>\s][ \t]+<(?P<address>'
21
- rb'noreply@(?:anthropic|github)\.com|'
21
+ rb'noreply@(?:anthropic|openai|github)\.com|'
22
22
  rb'[0-9]+\+[a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){0,38}@users\.noreply\.github\.com'
23
23
  rb')>[ \t]*\r?$', re.I | re.M)
24
24