@runeditrun/rer 0.2.112 → 0.2.113

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.
@@ -0,0 +1,18 @@
1
+ import { deployPermissions } from './deploy-needs.mjs';
2
+
3
+ // An offline plan knows the declared migrations, never which ones the hosted
4
+ // databases have applied. Keep that distinction in the human summary.
5
+ export function deployPlanLines(plan, declaration) {
6
+ const lines = ['Would deploy:', ` Worker: ${plan.worker}`];
7
+ for (const database of plan.d1) lines.push(` D1 database: ${database.name} (${database.migrations.length} declared migration${database.migrations.length === 1 ? '' : 's'})`);
8
+ if (!plan.d1.length) lines.push(' D1 databases: none');
9
+ for (const [kind, label] of [['r2', 'R2 storage'], ['kv', 'KV storage'], ['queues', 'Queue'], ['services', 'Worker service']]) {
10
+ for (const item of plan[kind]) lines.push(` ${label}: ${item.name ?? item.service}`);
11
+ }
12
+ if (plan.durableObjects.length) lines.push(` Durable Objects: ${plan.durableObjects.length}`);
13
+ lines.push(` Secret inputs: ${plan.secrets.filter(item => !item.optional).length} required, ${plan.secrets.filter(item => item.optional).length} optional`);
14
+ lines.push(` Public settings: ${plan.vars.length}; scheduled triggers: ${plan.crons.length}`);
15
+ lines.push(` Cloudflare token permissions: ${deployPermissions(declaration).join(', ')}`);
16
+ lines.push(' Pending migrations: unknown until the hosted databases are checked.');
17
+ return lines;
18
+ }
@@ -3,8 +3,9 @@ import { invalid } from './errors.mjs';
3
3
 
4
4
  // Seed policy is separate from uploading: secret-only commands bypass the
5
5
  // deploy hook, but must not bypass a seed's applicable local input policy.
6
- export async function enforceDeployPolicy({ adapter, root, options, setupManifest, localOnlyKeys, declaration, declarationPath, settings }) {
6
+ export async function enforceDeployPolicy({ adapter, root, options, store, setupManifest, localOnlyKeys, declaration, declarationPath, settings }) {
7
7
  if (adapter.deployPolicy === undefined) return;
8
+ await store.step('Checking deploy policy');
8
9
  if (typeof adapter.deployPolicy !== 'function') throw invalid('The adapter deployPolicy must be a function.');
9
10
  const { env } = await deployEnvironment({ root, options, declaration, setupManifest, settings, localOnlyKeys });
10
11
  // Resolve declared environment aliases before policy sees Worker bindings.
package/cli/deploy.mjs CHANGED
@@ -22,6 +22,8 @@ import { keptSecrets, keepSecrets, forgetSecrets } from './deploy-secrets.mjs';
22
22
  import { withoutLocalSettings, refuseLocalEnvOutput } from './local-env.mjs';
23
23
  import { deployProductDirectory, deployProductArguments } from './deploy-product.mjs';
24
24
  import { rotateInstallationKey, reopenInstallationKey, keepInstallationKey } from './deploy-installation-key.mjs';
25
+ import { deployPlanLines } from './deploy-plan.mjs';
26
+ import { relative } from 'node:path';
25
27
 
26
28
  export function ownerDeploy(declarationPath, lifecycle) {
27
29
  // rer verify serves the build with this declaration's vars and secrets.
@@ -69,7 +71,9 @@ export function ownerDeploy(declarationPath, lifecycle) {
69
71
  try {
70
72
  if (options.dryRun) {
71
73
  const {plan} = await owner('local-plan');
72
- store.report(`Would deploy: ${JSON.stringify(plan)}`);
74
+ store.report(`Deploy plan: ${JSON.stringify(plan)}`, { logOnly: true });
75
+ for (const line of deployPlanLines(plan, declaration)) store.report(line);
76
+ store.report(`Full plan: repeat this command with --json.${store.logPath ? ` Redacted capture log: ${relative(root, store.logPath)}` : ''}`);
73
77
  return { dryRun: true, deployed: false, providerChecked: false, plan };
74
78
  }
75
79
  // A custom hook's own state file, when its deploy named one.
@@ -1,12 +1,18 @@
1
+ import { shellQuote } from './node-runtime-cache.mjs';
1
2
  // The one line a finished export ends with: which copy it exported, the
2
3
  // archive, its size and what it holds.
3
- export function exportSummary({ target = 'local', origin, output, bytes, tables, hostedExport, childExitCode, exitCode = childExitCode } = {}) {
4
+ export function exportSummary({ target = 'local', origin, output, bytes, tables, captureLog, hostedExport, childExitCode, exitCode = childExitCode } = {}) {
4
5
  if (typeof output !== 'string') return undefined;
5
6
  const copy = target === 'remote' ? `the hosted install${origin ? ` at ${origin}` : ''}` : 'the local copy';
6
7
  if (hostedExport && Number.isInteger(exitCode)) return exitCode === 0 ? `Exported ${copy} to ${output} (exit 0)` : `Export of ${copy} to ${output} failed (exit ${exitCode})`;
7
8
  if (!Number.isSafeInteger(bytes) || !Array.isArray(tables)) return undefined;
8
9
  const rows = tables.reduce((sum, table) => sum + (Number.isSafeInteger(table?.count) ? table.count : 0), 0);
9
- return `Exported ${copy} to ${output} (${size(bytes)}): ${counted(tables.length, 'table')}, ${counted(rows, 'row')}`;
10
+ const file = /^[A-Za-z0-9_./-]+$/.test(output) ? output : shellQuote(output);
11
+ return [
12
+ `Exported ${copy} to ${output} (${size(bytes)}): ${counted(tables.length, 'table')}, ${counted(rows, 'row')}`,
13
+ captureLog && `Full output: ${captureLog}`,
14
+ `To restore into an empty installation: rer import --input ${file} --yes`,
15
+ ].filter(Boolean).join('\n');
10
16
  }
11
17
 
12
18
  const counted = (value, noun) => `${value.toLocaleString('en-US')} ${noun}${value === 1 ? '' : 's'}`;
@@ -1,4 +1,17 @@
1
1
  // Only declared safe replacement values and aggregate counts reach the terminal.
2
+ export function importSummary(details = {}) {
3
+ const { input, tables, target = 'local', objects, captureLog, nextCommand = 'rer setup' } = details;
4
+ if (typeof input !== 'string' || !Array.isArray(tables)) return undefined;
5
+ const rows = tables.reduce((sum, table) => sum + (Number.isSafeInteger(table?.count) ? table.count : 0), 0);
6
+ return [
7
+ `Restored ${target === 'local' ? 'the local copy' : 'the hosted install'} from ${input}: ${count(tables.length, 'table')}, ${count(rows, 'row')}${Number.isSafeInteger(objects) ? `, ${count(objects, 'file')}` : ''}.`,
8
+ importSafetySummary(details),
9
+ captureLog && `Full output: ${captureLog}`,
10
+ `Next: ${nextCommand}${target === 'local' ? ', then rer dev to open the restored app' : ''}.`,
11
+ ].filter(Boolean).join('\n');
12
+ }
13
+ const count = (value, noun) => `${value.toLocaleString('en-US')} ${noun}${value === 1 ? '' : 's'}`;
14
+
2
15
  export function importSafetySummary({safetyChanges}={}) {
3
16
  if(!safetyChanges?.length)return undefined;
4
17
  return safetyChanges.map(({table,column,value,rows})=>
package/cli/lifecycle.mjs CHANGED
@@ -82,7 +82,7 @@ async function runLifecycle(project, options, out, deployRedaction) {
82
82
  const directory = project.profile === 'first-party' && options.verb !== 'doctor' ? await privateDirectory(project.root, capture) : (temporary = await mkdtemp(join(tmpdir(), 'rer-command-')));
83
83
  const state = { logs: [] };
84
84
  const progress = text => { if (!installingFrozen || options.json) out.progress(text); };
85
- store = await createCommands(directory, state, { terminal: options.verb === 'deploy' && options.dryRun ? withoutPnpmChatter(progress) : progress, onWaiting: options.json ? details => out.event('waiting', details) : undefined, queue: ['install','setup','build','verify','deploy','export','import'].includes(options.verb)?{verb:options.verb,originalCI:process.env.CI==='true'}:undefined });
85
+ store = await createCommands(directory, state, { filterViteWarnings: options.verb === 'setup', filterArchiveReceipts: options.verb === 'export', terminal: options.verb === 'deploy' && options.dryRun ? withoutPnpmChatter(progress) : progress, onWaiting: options.json ? details => out.event('waiting', details) : undefined, queue: ['install','setup','build','verify','deploy','export','import'].includes(options.verb)?{verb:options.verb,originalCI:process.env.CI==='true'}:undefined });
86
86
  store.state = state;
87
87
  if (deployRedaction) store.addSecrets?.(Object.values(process.env).filter(value => value && deployRedaction.redact(value) !== value));
88
88
  store.setupManifest = project.setupManifest;
package/cli/output.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import { humanError } from './human-error.mjs';
2
2
  import { handleBrokenPipes } from './stdio.mjs';
3
3
  import { exportSummary } from './export-summary.mjs';
4
- import { importSafetySummary } from './import-summary.mjs';
4
+ import { importSummary, importSafetySummary } from './import-summary.mjs';
5
5
  export function output(options) {
6
6
  handleBrokenPipes();
7
7
  let finished = false;
@@ -21,7 +21,7 @@ export function output(options) {
21
21
  if (structuredResult) this.event('result', { ok, exitCode, ...details });
22
22
  // A finished export ends with one line naming its archive; the receipt is --json data.
23
23
  else if (options.verb === 'export' && (ok || details.hostedExport) && exportSummary({ ...details, exitCode })) this.human(exportSummary({ ...details, exitCode }));
24
- else if (ok && options.verb === 'import' && importSafetySummary(details)) this.human('import: complete (exit 0)\n' + importSafetySummary(details));
24
+ else if (ok && options.verb === 'import' && (importSummary(details) || importSafetySummary(details))) this.human(importSummary(details) || ('import: complete (exit 0)\n' + importSafetySummary(details)));
25
25
  else if (!['describe', 'check', 'dev', 'preview', 'setup'].includes(options.verb) || !ok) this.human(`${options.verb}: ${ok ? 'complete' : 'failed'} (exit ${exitCode})`);
26
26
  },
27
27
  error(error) {
@@ -65,7 +65,7 @@ export function localPortability({ database, binding = 'DB', buckets = {}, polic
65
65
  if(direction==='import' && !legacyRecovery) {
66
66
  try { await emptyNativePreflight(input); }
67
67
  catch(error) {
68
- if(error instanceof PortabilityError && error.code.startsWith('target_not_empty:'))throw new RerError('restore_refused',occupiedRefusal(input,'target_not_empty',error.code.slice(error.code.indexOf(':')+1)),4);
68
+ if(error instanceof PortabilityError && error.code.startsWith('target_not_empty:'))throw new RerError('restore_refused',occupiedRefusal(input,'target_not_empty'),4);
69
69
  if(error instanceof PortabilityError)throw refuse(`Local restore refused (${error.code}).`);
70
70
  throw error;
71
71
  }
@@ -109,12 +109,12 @@ async function nativeWorker(store,direction,input,signal) {
109
109
  : receipt.safety ? `Restore refused (${receipt.reason}): safety normalization for ${receipt.safety} violates the declared import policy.`
110
110
  : receipt.reason?.startsWith('migration_ledger:') ? ledgerRefusal(receipt)
111
111
  : receipt.migration ? `Restore refused (schema_mismatch:migration_data): migration ${receipt.migration} changed data after this archive was made, so its rows would skip that change. Restore an archive made after it.`
112
- : receipt.occupied ? occupiedRefusal(input,receipt.reason,receipt.occupied)
112
+ : receipt.occupied ? occupiedRefusal(input,receipt.reason)
113
113
  : `The portability module refused or failed the archive operation (${receipt.reason ?? 'incomplete'}${receipt.native ? `: ${receipt.native.class}${receipt.native.code && receipt.native.code !== receipt.reason ? `, code ${receipt.native.code}` : ''}` : ''}).${receipt.native && receipt.exitCode === 1 ? ' Run the same command again; it starts over.' : ''}`, receipt.exitCode ?? 1);
114
114
  delete receipt.ok;
115
115
  return receipt;
116
116
  }
117
117
 
118
- function occupiedRefusal(input,reason,occupied) {
119
- return `Restore refused (${reason}): ${reason === 'bucket_not_empty' ? `storage bucket ${occupied} in this installation already holds files` : `table ${occupied} in this installation already holds rows its migrations did not insert`}, and a restore only goes into an empty installation. To replace this installation's data with the archive, keep a copy with rer export --output exports/before-restore.rer, then run rer reset --yes and rer import --input ${relative(input.root, input.path)} --yes again.`;
118
+ function occupiedRefusal(input,reason) {
119
+ return `Restore refused (${reason}): this installation already contains ${reason === 'bucket_not_empty' ? 'files' : 'people or data'}. Import restores into an empty installation. Use a fresh installation, or to replace this installation's data, keep a copy with rer export --output exports/before-restore.rer, then run rer reset --yes and rer import --input ${relative(input.root, input.path)} --yes again.`;
120
120
  }
package/cli/transfers.mjs CHANGED
@@ -45,10 +45,10 @@ export async function transfer(project, options, signal, custody) {
45
45
  const operation = direction === 'import' && typeof api.managedDataImport === 'function' && await isManagedDataZip(path) ? api.managedDataImport : api[direction];
46
46
  const result=await operation.call(api, { root: project.root, target, path, journal, origin: options.origin, sessionFile, signal, platform:options.platform, legacyRecovery, acknowledgeUnverifiedSchemaObjects:options.acknowledgeUnverifiedSchemaObjects, ...custody });
47
47
  // The archive's size, for the line a finished export ends with.
48
- if(direction==='export')return {...result,target,...(target==='remote'&&options.origin?{origin:new URL(options.origin).origin}:{}),output:result.output??relative(project.root,path),bytes:(await stat(path)).size};
48
+ if(direction==='export')return {...result,target,...(target==='remote'&&options.origin?{origin:new URL(options.origin).origin}:{}),output:result.output??relative(project.root,path),bytes:(await stat(path)).size,captureLog:relative(project.root,custody.store.logPath)};
49
49
  if(direction==='import' && target==='local' && (await localDependencyLinks(project.root)).some(link=>link.needs_relink)) {
50
50
  custody.store.report('Imported provider links need fresh approval. Run rer setup with RER_LINK_TOKEN_FILE to re-link this installation.');
51
51
  return {...result,needsRelink:true,nextCommand:'rer setup'};
52
52
  }
53
- return result;
53
+ return direction === 'import' ? { ...result, captureLog: relative(project.root, custody.store.logPath), nextCommand: 'rer setup' } : result;
54
54
  }
@@ -1,5 +1,24 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.113
4
+
5
+ ### Recovery output and archive restore
6
+
7
+ - Installation restore refusals explain that the destination already contains people, data or files, without exposing internal table or bucket names. Restore still requires an empty installation: use a fresh installation, or keep a backup before the explicit reset and restore commands printed in the refusal.
8
+ - Successful local restore reports the archive, table/row counts, file counts when available, safety changes and the setup/dev next step. Wrangler SQL results stay in the redacted capture log; failed queries keep their diagnostics. Setup keeps Vite source-import advisories and suppression instructions in that log while retaining unrelated warnings and errors.
9
+ - Local installation export keeps seed-owned worker success JSON in the redacted capture log and prints a readable archive receipt, its log path and a directly runnable `rer import --input FILE --yes` command for an empty installation. Paths needing shell quoting are quoted. The full structured receipt remains available with `--json`. Archive format is unchanged; this does not repair seed-owned restore validators.
10
+
11
+ ### Deploy plans and first-run startup
12
+
13
+ - `rer deploy --dry-run` prints the Worker, declared product resources, required token permissions, settings/secret counts and declared migration counts. Pending migrations remain unknown offline; the full structured plan stays in the redacted capture log and `--json`. Dry-run recovery retains `--dry-run`; real-deploy recovery retains its existing command. Ordinary seed deploy-policy failures now name `Checking deploy policy` and stop before provider contact; missing-input refusals retain exit 3. Setup token-permission coverage follows the seed's resource declaration, including R2 and Queues.
14
+ - Managed development targets that use the listener handshake without an explicit timeout now get the shared target's first-run readiness window and explain dependency optimization while waiting. Readiness still awaits the real application listener and health check.
15
+
16
+ ### Erasure archive preflight
17
+
18
+ - Shared portability import creation refuses an already-stale erasure archive before schema inventory and durable restore staging. The early epoch check is read-only and the final erasure fence remains in place. The reference emitted-Worker person-erasure journey advances more export parts per call without relaxing its assertions or timeout.
19
+
20
+ Seeds receive these CLI and shared-module changes only after adopting this rer through their pinned package or refreshed source. No seed adoption, deployed behavior or production result is established here. The actual diff adds no migrations; previously released export allocation/ETA and duplicate mail-key wording fixes are not new in 0.2.113.
21
+
3
22
  ## 0.2.112
4
23
 
5
24
  ### Downloaded tools and export progress
@@ -11,7 +11,7 @@ import { platformTable, restorableManifest } from './bookkeeping.mjs';
11
11
  import { withoutAbsentExcludedObjects } from './snapshot-objects.mjs';
12
12
  import { canonicalJson, unbase64 } from './hash.mjs';
13
13
  import { checkManifest, checkPart, ContentVerifier, ArchiveVerifier } from './format.mjs';
14
- import { fence, mergeJournal, tombstone } from './journal.mjs';
14
+ import { checkEpoch, fence, mergeJournal, tombstone } from './journal.mjs';
15
15
  import { writeObject } from './payloads.mjs';
16
16
  import { createCopy,sidecar,readCopy,restoreCopy } from './copies.mjs';
17
17
  import { excludedDependentGuards, migrationSeeded, seededCondition } from './restore-safety.mjs';
@@ -26,6 +26,9 @@ import { rebuildDerivedStatements } from './derived.mjs';
26
26
  export async function createImport(context,manifest,actor='direct',legacyRecovery,ledgers,acknowledgeUnverifiedSchemaObjects=false,id=crypto.randomUUID()) {
27
27
  const {db,config,buckets}=context;await checkManifest(manifest);checkArchivedLedgers(manifest,ledgers);
28
28
  insist(manifest.product===config.product,'wrong_product');
29
+ // An already-stale backup cannot become restorable. Refuse before schema
30
+ // inventory, staging copies and part uploads; fence checks again at finalize.
31
+ await checkEpoch(db,manifest);
29
32
  // Explicit schema upgrades can reconcile rows, but cannot attest an interrupted deployment.
30
33
  await appliedMigrations(db);
31
34
  const original=manifest;manifest=await restorableManifest(original,{canonical:true});
@@ -21,10 +21,13 @@ export async function invalidateTransfersStatements(db) {
21
21
  export async function journal(db,source) {
22
22
  return (await all(db,'SELECT tombstone FROM rer_portability_journal WHERE source=? ORDER BY tombstone',source)).map(x=>x.tombstone);
23
23
  }
24
- export async function fence(db,manifest,copies,later) {
24
+ export async function checkEpoch(db,manifest) {
25
25
  const recorded=await statement(db,'SELECT epoch FROM rer_portability_epochs WHERE source=?',manifest.sourceIdentity).first();
26
- const s=await state(db);
27
- insist(manifest.epoch>=Math.max(recorded?.epoch??0,s.source_identity===manifest.sourceIdentity?s.epoch:0),'erasure_epoch');
26
+ const s=await statement(db,'SELECT source_identity,epoch FROM rer_portability_state WHERE id=1').first();
27
+ insist(manifest.epoch>=Math.max(recorded?.epoch??0,s?.source_identity===manifest.sourceIdentity?s.epoch:0),'erasure_epoch');
28
+ }
29
+ export async function fence(db,manifest,copies,later) {
30
+ await checkEpoch(db,manifest);
28
31
  if(later) insist(later.sourceIdentity===manifest.sourceIdentity && Number.isSafeInteger(later.epoch) && later.epoch>=manifest.epoch && Array.isArray(later.journal),'later_journal');
29
32
  const hashes=new Set([...manifest.journal,...await journal(db,manifest.sourceIdentity),...(later?.journal??[])]);
30
33
  insist([...hashes].every(x=>/^[a-f0-9]{64}$/.test(x)),'invalid_journal');
@@ -233,7 +233,11 @@ async function start(context, hooks) {
233
233
  try{return await listenerPorts(child.pid);}
234
234
  catch(error){throw installationFailure('command_failed',{step:'start',diagnostic:error});}
235
235
  };
236
- const readinessTimeoutMs=timeoutMs??60000,readinessStarted=performance.now();
236
+ // A seed can use the managed IPC handshake without developmentTarget's
237
+ // options (Uptime does). Give that real listener/health journey the same
238
+ // first-run budget, including Vite dependency optimization.
239
+ const readinessTimeoutMs=timeoutMs??(runtimePortHandshake?900000:60000),readinessStarted=performance.now();
240
+ if(runtimePortHandshake)store.report('Waiting for the application server to finish starting; first launch may optimize dependencies.');
237
241
  try {
238
242
  await store.waitForReady(readinessLabel, child, async probeSignal => {
239
243
  if(runtimePortHandshake){
@@ -0,0 +1,76 @@
1
+ // Views run after redaction. The command store still writes every original
2
+ // redacted byte to install.log; only the person's progress is shortened here.
3
+ export function isWranglerQuery(command, args = []) {
4
+ const words = [command, ...args].map(String);
5
+ const tool = words.findIndex(word => /(^|[\\/])wrangler(\.js)?$/.test(word));
6
+ return tool >= 0 && words.slice(tool + 1).some((word, index, rest) => word === 'd1' && rest[index + 1] === 'execute');
7
+ }
8
+
9
+ export function wranglerQueryView({ log }) {
10
+ let tail = '';
11
+ return {
12
+ write(text) { tail = (tail + text).slice(-32768); return ''; },
13
+ end({ code, signal, error } = {}) {
14
+ // A failed SQL command must keep its actual diagnostic, including its exit
15
+ // status in the command store. Successful query JSON is never user output.
16
+ return code !== 0 || signal || error ? tail : `Database update complete. Full output: ${log}\n`;
17
+ },
18
+ };
19
+ }
20
+
21
+ // Vite emits multiline source-import advisories during setup. Keep both their
22
+ // source frames and suppression instructions in the capture, without hiding
23
+ // unrelated warnings or errors. A partial/unrecognized block stays visible.
24
+ export function viteDiagnosticsView(inner) {
25
+ let pending = '', block = '', kind;
26
+ const emit = text => inner ? inner.write(text) : text;
27
+ const line = text => {
28
+ if (!kind && /\[vite\].*warning:/.test(text)) kind = 'import';
29
+ if (!kind && /Your Vite config uses features that are unsupported by/.test(text)) kind = 'config';
30
+ if (!kind) return emit(text);
31
+ block += text;
32
+ const complete = kind === 'import' ? /^\s*File:/.test(text) : /VITE_CONFIG_NATIVE_IGNORE_WARNING.*suppress this warning/.test(text);
33
+ if (!complete && block.length < 32768) return '';
34
+ const advisory = kind === 'config' || /The above dynamic import cannot be analyzed by Vite/.test(block);
35
+ const result = advisory && complete ? '' : emit(block);
36
+ block = ''; kind = undefined;
37
+ return result;
38
+ };
39
+ return {
40
+ write(text) {
41
+ const lines = (pending + text).split('\n'); pending = lines.pop();
42
+ return lines.map(item => line(item + '\n')).join('');
43
+ },
44
+ end(result) {
45
+ const rest = (pending ? line(pending) : '') + (block ? emit(block) : '');
46
+ pending = ''; block = ''; kind = undefined;
47
+ return rest + (inner?.end(result) ?? '');
48
+ },
49
+ facts: () => inner?.facts?.() ?? {},
50
+ };
51
+ }
52
+
53
+ // Seed-owned archive workers may send their success receipt on stdout. It is
54
+ // protocol data, retained by the command store's redacted log; progress and
55
+ // failed receipts still belong in the terminal.
56
+ export function archiveReceiptView(inner) {
57
+ let pending = '';
58
+ const emit = text => inner ? inner.write(text) : text;
59
+ const line = text => {
60
+ let receipt;
61
+ try { receipt = JSON.parse(text); } catch { return emit(text); }
62
+ return receipt?.ok === true && typeof receipt.contentHash === 'string' && Array.isArray(receipt.tables)
63
+ ? '' : emit(text);
64
+ };
65
+ return {
66
+ write(text) {
67
+ const lines = (pending + text).split('\n'); pending = lines.pop();
68
+ return lines.map(item => line(item + '\n')).join('');
69
+ },
70
+ end(result) {
71
+ const rest = pending ? line(pending) : ''; pending = '';
72
+ return rest + (inner?.end(result) ?? '');
73
+ },
74
+ facts: () => inner?.facts?.() ?? {},
75
+ };
76
+ }
@@ -12,8 +12,9 @@ import { commandCustody } from './command-custody.mjs';
12
12
  import { createProcessBaseline, createProcessScope, inheritedScopeTokens, processScopeEnvironment } from './process-scope.mjs';
13
13
  import { toolCommand } from './tool-command.mjs';
14
14
  import { isWranglerMigrationApply, wranglerMigrationView } from './migration-progress.mjs';
15
+ import { isWranglerQuery, wranglerQueryView, viteDiagnosticsView, archiveReceiptView } from './command-diagnostics-view.mjs';
15
16
 
16
- export async function createCommands(directory,state,{terminal=text=>writeSync(1,text),spawn=spawnChild,queue:queuePolicy,custodyToken,onWaiting}={}) {
17
+ export async function createCommands(directory,state,{terminal=text=>writeSync(1,text),spawn=spawnChild,queue:queuePolicy,custodyToken,onWaiting,filterViteWarnings=false,filterArchiveReceipts=false}={}) {
17
18
  let policy=queuePolicy?await commandPolicy():{environment:{},close:async()=>{}};
18
19
  const custodyBaseline=['darwin','linux'].includes(process.platform)?await createProcessBaseline():undefined;
19
20
  const logPath=join(directory,'install.log'), log=await openPrivateLog(logPath);
@@ -58,7 +59,10 @@ export async function createCommands(directory,state,{terminal=text=>writeSync(1
58
59
  for(const match of text.matchAll(pattern)){result+=redaction.redact(text.slice(from,match.index))+match[0];from=match.index+match[0].length;}
59
60
  return result+redaction.redact(text.slice(from));
60
61
  };
61
- const report=(text,{names}={})=>emit(redactBesideNames(String(text),names)+'\n');
62
+ const report=(text,{names,logOnly=false}={})=>{
63
+ const line=redactBesideNames(String(text),names)+'\n';
64
+ emit(logOnly?'':line,line);
65
+ };
62
66
  const failure=(label,detail={},capture)=>{
63
67
  const outcome=`exit ${detail.code??'none'}, signal ${detail.signal??'none'}`;
64
68
  const status=detail.reason==='cancel'?`cancelled (${outcome})`:detail.reason==='deadline'?`readiness deadline exceeded (${outcome})`:detail.error?`could not start${detail.errorCode?` (${detail.errorCode})`:''} (${outcome})`:outcome;
@@ -69,6 +73,8 @@ export async function createCommands(directory,state,{terminal=text=>writeSync(1
69
73
  };
70
74
  const track=(label,child,ownershipScope,view)=>{
71
75
  if(captures.has(child))return child;
76
+ if(filterViteWarnings)view=viteDiagnosticsView(view);
77
+ if(filterArchiveReceipts)view=archiveReceiptView(view);
72
78
  let resolveClose,resolveError,resolveExit;
73
79
  const capture={tail:'',scope:signal,closed:new Promise(resolve=>{resolveClose=resolve;}),failed:new Promise(resolve=>{resolveError=resolve;}),exited:new Promise(resolve=>{resolveExit=resolve;})};
74
80
  capture.custody=commandCustody(child,ownershipScope);
@@ -90,7 +96,7 @@ export async function createCommands(directory,state,{terminal=text=>writeSync(1
90
96
  child.removeListener('exit',exited);if(!capture.exitResult)exited(code,terminationSignal);
91
97
  for(const source of sources)source.removeListener('data',data);
92
98
  filter.end();
93
- if(view){const rest=view.end();capture.tail=(capture.tail+rest).slice(-32768);emit(rest,'');Object.assign(state,view.facts?.());}
99
+ if(view){const rest=view.end({code,signal:terminationSignal,error});capture.tail=(capture.tail+rest).slice(-32768);emit(rest,'');Object.assign(state,view.facts?.());}
94
100
  active.delete(child);if(!capture.custody)managed.delete(child);resolveClose({code,signal:terminationSignal,error,errorCode:capture.errorCode});
95
101
  };
96
102
  child.once('close',finish);
@@ -167,6 +173,7 @@ export async function createCommands(directory,state,{terminal=text=>writeSync(1
167
173
  // Any caller's `wrangler d1 migrations apply` (the setup hooks, a seed's own export and import) shows
168
174
  // a count instead of wrangler's table redrawn per migration; the log keeps every byte and is named in the summary.
169
175
  if(!options.view&&isWranglerMigrationApply(command,args))options={...options,view:()=>wranglerMigrationView({log:redaction.redact(checkoutPath(options.cwd??process.cwd(),logPath))})};
176
+ if(!options.view&&isWranglerQuery(command,args))options={...options,view:()=>wranglerQueryView({log:redaction.redact(checkoutPath(options.cwd??process.cwd(),logPath))})};
170
177
  if(queuePolicy && options.heavy !== false) {
171
178
  let queuedChild;
172
179
  const commandSignal=signal&&options.signal?AbortSignal.any([signal,options.signal]):options.signal||signal;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runeditrun/rer",
3
- "version": "0.2.112",
3
+ "version": "0.2.113",
4
4
  "description": "The rer command: install, set up, run and launch Run Edit Run checkouts.",
5
5
  "license": "MIT",
6
6
  "type": "module",