@runeditrun/rer 0.2.11 → 0.2.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli/contract.mjs CHANGED
@@ -11,7 +11,7 @@ const definitions = {
11
11
  build: [['--site'], 'Production build with private local settings excluded and restored. --site instead writes the static run site (homepage, /run, docs) to its declared folder and prints that folder.'],
12
12
  verify: [[], 'Run the complete internal verification target.'],
13
13
  reset: [['--yes'], 'Confirmed removal of the declared local inventory only.'],
14
- deploy: [['--environment', '--dry-run', '--site', '--demo', '--host', '--env-file', '--image', '--bind-address', '--http-port', '--https-port', '--remove', '--yes', '--set-secret', '--unset-secret'], 'Owner-account deployment and health; dry run performs local validation/build only. Declared secrets come from the environment or --env-file (an owned 0600 KEY=VALUE file); a new Worker gets the local setup owner and fresh generated secrets when they are not given. After a healthy deploy rer claims the setup owner on the hosted app with the one-time setup token, then removes the token. --set-secret NAME (value from the environment or --env-file) and --unset-secret NAME change one secret of the deployed Worker without a build and record its new version. --remove --yes deletes what this environment\'s deploy record says rer created (Worker, D1, R2, KV, queues), reads back that each is gone, and touches nothing else. --site deploys the run site instead: an assets-only Worker on its custom domain with www redirected; with --dry-run it builds the site and prints the plan with no provider request. --demo deploys the hosted demo instead (deploy-demo.json): a front Worker on demo.<domain> giving each visitor their own signed-in, throwaway container of this seed that can send nothing; --dry-run writes it to .rer/demo-host with no provider request.'],
14
+ deploy: [['--environment', '--dry-run', '--site', '--demo', '--host', '--env-file', '--image', '--bind-address', '--http-port', '--https-port', '--remove', '--yes', '--set-secret', '--unset-secret'], 'Owner-account deployment and health; dry run performs local validation/build only. Declared secrets come from the environment or --env-file (an owned 0600 KEY=VALUE file); a new Worker gets the local setup owner and fresh generated secrets when they are not given. After a healthy deploy rer claims the setup owner on the hosted app with the one-time setup token, then removes the token. --set-secret NAME (value from the environment or --env-file) and --unset-secret NAME change one secret of the deployed Worker without a build and record its new version. --remove --yes deletes what this environment\'s deploy record says rer created (Worker, D1, R2, KV, queues), reads back that each is gone, and touches nothing else. --site deploys the run site instead: an assets-only Worker on its custom domain with www redirected; with --dry-run it builds the site and prints the plan with no provider request. --demo deploys the hosted demo instead (deploy-demo.json): a front Worker on demo.<domain> giving each visitor their own signed-in, throwaway container of this seed that can send nothing; --dry-run writes it to .rer/demo-host with no provider request; --demo --remove --yes deletes that demo (its Worker, demo.<domain> Custom Domain and Container application, each only while the record its deploy left proves it the demo\'s), reads back that each is gone, and is a no-op once it is.'],
15
15
  export: [['--target', '--output', '--origin', '--session-file'], 'Complete supported installation archive with integrity and exclusions.'],
16
16
  import: [['--target', '--input', '--journal', '--origin', '--session-file', '--yes', '--legacy-v1', '--acknowledge-unverified-metadata', '--output'], 'Confirmed atomic restore into an empty destination; --journal LATER_ARCHIVE also fences rows that installation erased since. Backup-only local v1 recovery requires --legacy-v1 --acknowledge-unverified-metadata and a new --output v2 archive; --journal requires normal v2 import.'],
17
17
  outbox: [['--port', '--host', '--owner-email', '--open'], 'Credential-free local outbox URL; optional ordinary sign-in request and explicit browser opening.'],
package/cli/demo-host.mjs CHANGED
@@ -10,7 +10,9 @@ import { DEMO_FILES, demoPlan } from '../modules/demo-host/plan.mjs';
10
10
  // (modules/demo-host), from deploy-demo.json. It writes .rer/demo-host/: the
11
11
  // front Worker, its wrangler.json and the container image folder (workerd
12
12
  // engine). --dry-run stops there, so `wrangler dev` can serve that folder with
13
- // Docker; a deploy runs `wrangler deploy` on it with the Turnstile secret.
13
+ // Docker; a deploy runs `wrangler deploy` on it with the Turnstile secret and
14
+ // the demo's record as the version message. `--remove --yes` removes what that
15
+ // record proves is the demo's (modules/demo-host/remove.mjs).
14
16
  export async function demoHostCommand(project, options, store, signal, out, operation) {
15
17
  const read = async path => { try { return JSON.parse(await readFile(await contained(project.root, path), 'utf8')); } catch (error) { if (error instanceof RerError) throw error; throw invalid(`Missing or malformed ${path}.`); } };
16
18
  const app = await read(project.adapter.deploy?.declaration ?? 'deploy.json'), declaration = await read('deploy-demo.json');
@@ -18,6 +20,7 @@ export async function demoHostCommand(project, options, store, signal, out, oper
18
20
  let plan;
19
21
  try { plan = demoPlan({ project: app.project, environment: options.environment ?? 'production', compatibilityDate: app.compatibilityDate, originVar: app.originVar, declaration, turnstileSiteKey: process.env.TURNSTILE_SITE_KEY?.trim() }); }
20
22
  catch (error) { throw invalid(`The demo deploy declaration is invalid (${error.message}). deploy-demo.json holds {"version": 1, "domain": "<run site apex>", "name": "<product name>"}, optionally "maxInstances" and plain "settings".`); }
23
+ if (options.remove) return removeDemo(plan, store);
21
24
  if (process.env.RER_DEMO_OPERATOR_TOKEN && (process.env.RER_DEMO_OPERATOR_TOKEN.length < 32 || process.env.RER_DEMO_OPERATOR_TOKEN.length > 512)) throw invalid('RER_DEMO_OPERATOR_TOKEN must contain 32 to 512 characters.');
22
25
  const folder = join(project.root, '.rer', 'demo-host');
23
26
  await rm(folder, { recursive: true, force: true });
@@ -44,7 +47,26 @@ export async function demoHostCommand(project, options, store, signal, out, oper
44
47
  const require = createRequire(join(project.root, 'package.json'));
45
48
  const manifest = require.resolve('wrangler/package.json');
46
49
  const wrangler = join(dirname(manifest), JSON.parse(await readFile(manifest, 'utf8')).bin.wrangler);
47
- await store.run('Deploying the demo Worker and its container image', process.execPath, [wrangler, 'deploy', '--config', 'wrangler.json', '--secrets-file', '.secrets.json'], { cwd: folder, signal });
50
+ await store.run('Deploying the demo Worker and its container image', process.execPath, [wrangler, 'deploy', '--config', 'wrangler.json', '--secrets-file', '.secrets.json', '--message', plan.record], { cwd: folder, signal });
48
51
  } finally { await rm(secrets, { force: true }); }
49
52
  return { dryRun: false, deployed: true, origin: plan.origin, demo: summary };
50
53
  }
54
+
55
+ async function removeDemo(plan, store) {
56
+ const names = ['CLOUDFLARE_ACCOUNT_ID', 'CLOUDFLARE_API_TOKEN'];
57
+ if (names.some(name => !process.env[name]?.trim())) throw missing(`${names.join(' and ')} are required to remove the demo; see DEMO.md "Removing a hosted demo".`);
58
+ const { cloudflare } = await import('../modules/deploy-kit/provider.mjs');
59
+ const { providerRefusal } = await import('../modules/deploy-kit/diagnostics.mjs');
60
+ const { demoRemove } = await import('../modules/demo-host/remove.mjs');
61
+ await store.step(`Removing the demo Worker ${plan.worker} on ${plan.hostname}`);
62
+ let result;
63
+ try { result = await demoRemove({ api: cloudflare({ accountId: process.env.CLOUDFLARE_ACCOUNT_ID, token: process.env.CLOUDFLARE_API_TOKEN }), plan }); }
64
+ catch (error) {
65
+ if (error instanceof RerError) throw error;
66
+ const code = /^[a-z0-9-]{1,80}$/.test(error.message) ? error.message : 'demo-remove-failed';
67
+ const detail = [error.resource && `(${error.resource})`, error.remaining?.length && `still listed: ${error.remaining.join(', ')}`, providerRefusal(error)].filter(Boolean).join('; ');
68
+ throw new RerError('deploy_refused', `Demo remove stopped: ${code}${detail ? ` ${detail}` : ''}. Nothing that is not the demo's was touched; run it again once the cause is fixed.`, 1);
69
+ }
70
+ store.report(result.alreadyRemoved ? `deploy --demo --remove: no demo Worker ${plan.worker} exists; nothing to remove.` : `Removed ${result.removed.join(', ')} and read back that each is gone.`);
71
+ return { removed: true, demo: { worker: plan.worker, hostname: plan.hostname }, deleted: result.removed, alreadyRemoved: Boolean(result.alreadyRemoved) };
72
+ }
@@ -4,6 +4,7 @@ import { invalid, refuse, RerError } from './errors.mjs';
4
4
  import { ownerDeploy } from './deploy.mjs';
5
5
  import { deployEnvironment, deployAgain } from './deploy-inputs.mjs';
6
6
  import { claimHostedOwner } from './deploy-owner.mjs';
7
+ import { checkHostedSetup, hostedSetupFailure } from './deploy-setup.mjs';
7
8
  import { mutationReadinessFailure } from './deploy-readiness.mjs';
8
9
  import { observeOwner } from './deploy-observation.mjs';
9
10
  import { committedSource } from './deploy-source.mjs';
@@ -97,6 +98,8 @@ export async function deployCommand(context) {
97
98
  const kit = state ? { secret: (extra, values) => command('secret', extra, values), recordClaim: outcome => command('record-owner', ['--outcome', outcome]) } : { token: deployed.setupToken || undefined };
98
99
  claimed = await claimHostedOwner({ hook: adapter.hooks?.owner, setupManifest, declaration, deployed: { ...state, origin, owner: claimed, observedOwner: () => claims.at(-1)?.outcome }, env, supplied, ...kit, addSecret, beforeClaim: token => link(token, origin), store, signal: context.signal });
99
100
  if (!linked) await linkDependencies?.(origin);
101
+ step = 'verify hosted setup';
102
+ await checkHostedSetup({ origin, claimed: claimed ?? state?.ownerClaim?.outcome ?? claims.at(-1)?.outcome, signal: context.signal });
100
103
  if (claimed) store.report(`${claimed === 'claimed' ? 'Claimed the hosted owner' : 'The hosted owner was already claimed and was kept'}${state ? '; the one-time setup token was removed' : ''}. Sign in by email at ${origin}.`);
101
104
  const { setupToken: _, ...result } = deployed;
102
105
  return { ...result, ...(claimed ? { owner: claimed } : {}), dependenciesLinked: true };
@@ -109,6 +112,8 @@ export async function deployCommand(context) {
109
112
  const outcome = error.owner ?? claimed ?? observedClaims.at(-1)?.outcome;
110
113
  const state = deployed?.deployed || recorded ? `The application is deployed at ${deployed?.origin ?? recorded.origin}; ${outcome ? `owner ${outcome}` : 'owner claim is not confirmed'}${recorded ? '; setup token retirement is not confirmed' : ''}.` : 'The custom deploy did not finish; inspect its deployment record before recovery.';
111
114
  const redact = value => store.redact?.(redaction.redact(value)) ?? redaction.redact(value);
115
+ const setup = hostedSetupFailure(error, { origin: deployed?.origin ?? recorded?.origin, again });
116
+ if (setup) throw commandFailure(redact(setup));
112
117
  const readiness = mutationReadinessFailure(error, { again, redact });
113
118
  if (readiness) throw commandFailure(readiness);
114
119
  const refused = providerRefusal(error);
@@ -0,0 +1,25 @@
1
+ // Some native apps expose setup status without registering a shared owner step.
2
+ // An explicit unfinished setup must not become deploy success just because
3
+ // /health is healthy. An absent or unsupported endpoint proves nothing either
4
+ // way and remains compatible with apps that do not implement this optional API.
5
+ export async function checkHostedSetup({ origin, claimed, signal }) {
6
+ if (['claimed', 'kept'].includes(claimed)) return;
7
+ let required = false;
8
+ try {
9
+ const response = await globalThis.fetch(new URL('/api/identity/setup-status', origin), {
10
+ method: 'GET', credentials: 'omit', redirect: 'manual',
11
+ headers: { Accept: 'application/json', 'Cache-Control': 'no-cache' },
12
+ signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(10000)]) : AbortSignal.timeout(10000),
13
+ });
14
+ // Never follow a redirect or interpret an error page as a setup contract.
15
+ if (!response.redirected && (response.ok || response.status === 409)) required = (await response.json())?.setupRequired === true;
16
+ else await response.body?.cancel();
17
+ } catch { /* Only an explicit setup-required response establishes this gap. */ }
18
+ signal?.throwIfAborted();
19
+ if (required) throw new Error('hosted-setup-required');
20
+ }
21
+
22
+ export function hostedSetupFailure(error, { origin, again }) {
23
+ if (error.message !== 'hosted-setup-required') return undefined;
24
+ return `Deploy is incomplete. The application is deployed at ${origin}, but /api/identity/setup-status reports that setup is required and the owner claim is not confirmed. The deployed resources are retained for recovery. Fix or register the application's actual native owner-claim integration in its adapter and setup manifest, then rerun ${again} using the same environment credentials.`;
25
+ }
package/cli/deploy.mjs CHANGED
@@ -8,6 +8,7 @@ import { packageBuild } from '../modules/deploy-kit/prepare.mjs';
8
8
  import { refuseLocalModels } from '../modules/deploy-kit/local-only.mjs';
9
9
  import { deployEnvironment, deployAgain } from './deploy-inputs.mjs';
10
10
  import { claimHostedOwner } from './deploy-owner.mjs';
11
+ import { checkHostedSetup, hostedSetupFailure } from './deploy-setup.mjs';
11
12
  import { mutationReadinessFailure } from './deploy-readiness.mjs';
12
13
  import { committedSource } from './deploy-source.mjs';
13
14
  import { hookState, forgetHookState } from './deploy-hook-record.mjs';
@@ -79,7 +80,6 @@ export function ownerDeploy(declarationPath, lifecycle) {
79
80
  if (sent.length) store.report(`rer supplied ${sent.join(', ')} from the local setup owner and fresh generated values.`);
80
81
  step = 'health';
81
82
  await owner('health');
82
- store.report(`Your application is live on your Cloudflare account at ${deployed.origin}.`);
83
83
  step = 'claim owner';
84
84
  const { liveSecrets, retiredSecrets, ownerClaim } = await owner('inspect');
85
85
  const linked = token => linkDependencies?.(deployed.origin, token);
@@ -87,6 +87,9 @@ export function ownerDeploy(declarationPath, lifecycle) {
87
87
  secret: (extra, values) => owner('secret', extra, values), beforeClaim: linked, recordClaim: outcome => owner('record-owner', ['--outcome', outcome]), inspect: () => owner('inspect'), store, signal });
88
88
  // A seed that claims its owner its own way links with the token it was given.
89
89
  if (claimed === undefined) await linked(env[declared(claim?.tokenField ?? 'SETUP_TOKEN')?.environment]);
90
+ step = 'verify hosted setup';
91
+ await checkHostedSetup({ origin: deployed.origin, claimed: claimed ?? ownerClaim?.outcome, signal });
92
+ store.report(`Your application is live on your Cloudflare account at ${deployed.origin}.`);
90
93
  // The app claims the OWNER_EMAIL the Worker holds: the local one only when this run uploaded it.
91
94
  const email = declared(claim?.emailField);
92
95
  const named = !email ? '' : deployed.sentSecrets.includes(email.binding) && env[email.environment] ? ` (${env[email.environment]})` : ` (the ${email.binding} already set on the Worker)`;
@@ -102,6 +105,8 @@ export function ownerDeploy(declarationPath, lifecycle) {
102
105
 
103
106
  // The failing step, its redacted cause, what this run created and the command that continues.
104
107
  function failureText({ error, step, created, again, retry, secretChange, deployed, redact }) {
108
+ const setup = hostedSetupFailure(error, { origin: deployed?.origin, again });
109
+ if (setup) return redact(setup);
105
110
  const readiness = mutationReadinessFailure(error, { again, redact });
106
111
  if (readiness) return readiness;
107
112
  const diagnostic = deployDiagnostic(error, redact);
package/cli/parse.mjs CHANGED
@@ -77,7 +77,8 @@ export function parse(argv, cwd = process.cwd(), { independent = false, deferTai
77
77
  if (options.profile !== undefined && options.profile !== 'first-party') throw invalid('The supported explicit profile is first-party.');
78
78
  if (options.environment !== undefined && !/^[a-z][a-z0-9-]{0,39}$/.test(options.environment)) throw invalid('Provide a valid deployment environment name.');
79
79
  for (const key of ['setSecret', 'unsetSecret']) if (options[key] !== undefined && !/^[A-Z][A-Z0-9_]{0,63}$/.test(options[key])) throw invalid('Name a declared secret binding, such as SESSION_SECRET.');
80
- if(verb==='deploy'&&options.demo&&(options.site||['platform','image','bindAddress','httpPort','httpsPort','envFile','host','remove','setSecret','unsetSecret'].some(key=>options[key]!==undefined)))throw invalid('--demo takes only --environment and --dry-run: the hosted demo is its own Worker on demo.<domain>.');
80
+ if(verb==='deploy'&&options.demo&&(options.site||['platform','image','bindAddress','httpPort','httpsPort','envFile','host','setSecret','unsetSecret'].some(key=>options[key]!==undefined)))throw invalid('--demo takes only --environment, --dry-run and --remove --yes: the hosted demo is its own Worker on demo.<domain>.');
81
+ if(verb==='deploy'&&options.demo&&options.remove&&(options.dryRun||!options.yes))throw invalid(options.dryRun?'Use --remove and --dry-run on separate runs.':'deploy --demo --remove deletes the hosted demo\'s Worker, its demo.<domain> Custom Domain and its Container application. Add --yes to confirm.');
81
82
  if ((options.remove || options.setSecret || options.unsetSecret) && options.site) throw invalid('--remove, --set-secret and --unset-secret act on the application Worker, not the run site.');
82
83
  if (options.origin !== undefined) {
83
84
  let url; try { url = new URL(options.origin); } catch { throw invalid('Provide a valid credential-free origin.'); }
@@ -1,5 +1,26 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.13
4
+
5
+ - `rer deploy --remove` accepts empty owned R2 object listings without pagination metadata, fixing the 0.2.9 regression. Populated or malformed listings still require complete pagination proof before deletion.
6
+ - Workerd container images may use `HTMLRewriter`, including hosted demo images. Engines without that API still refuse it.
7
+ - A deploy whose hosted app explicitly reports setup required without a confirmed owner claim exits 1 with the recovery step. The live announcement follows owner handling and the setup check.
8
+
9
+ ### Upgrade notes
10
+
11
+ - Update the rer package to receive these deploy fixes. An app with an unregistered native owner claim still needs that integration repaired; rer now reports the incomplete deployment and retains its resources for recovery.
12
+
13
+ ## 0.2.12
14
+
15
+ - Import-kit resumable field redaction finishes however large one import job is. A step takes as many jobs as fit the request (at most 25); a job that does not fit alone is redacted in pages of its entries, and a step that would not fit writes nothing and is retried smaller, so every committed step stays inside D1's per-request limit and the erasure reaches its final batch. Receipts and match counts are unchanged.
16
+ - `rer deploy --demo --remove --yes [--environment E]` removes a hosted demo: its Custom Domain (and with it the domain's DNS record), its Container application and its Worker, each by exact id and only while the record the deploy left on the Worker version proves it the demo's. Anything else is refused before the first delete; a second run is a no-op.
17
+ - `export/run-demo.yml` gains `test_only` (the demo-test host at `demo.test.<domain>`) and `remove` dispatch inputs, and its readback after a deploy waits for the new hostname to resolve in public DNS, bounded and with a clear message, instead of failing on a first deploy.
18
+
19
+ ### Upgrade notes
20
+
21
+ - Seeds take the import-kit change with their next Base refresh (a vendored `modules/import-kit` copy is not replaced by the npm pin). A continuation stored by an earlier kit still reads.
22
+ - A hosted demo deployed by an earlier rer carries no record, so `--remove` refuses it as not the demo's: deploy it once with 0.2.12 (`rer deploy --demo`, or run-demo with the same inputs), then remove it. Copy Base's `export/run-demo.yml` for the new inputs and readback; a manual run no longer needs `RUN_DEMO_DEPLOY`.
23
+
3
24
  ## 0.2.11
4
25
 
5
26
  - New Base foundations generate public Run instructions for the edition's planned product repository, distinct migration ordinals, and setup names matching the edition.
@@ -25,7 +25,7 @@ export async function checkBoundary(root, { engine='node', cacheContract }={}) {
25
25
  }
26
26
  }
27
27
  if(ts.isCallExpression(node)&&node.arguments.some(arg=>ts.isStringLiteral(arg)&&arg.text.startsWith('cloudflare:')))fail('Dynamic Cloudflare import');
28
- if(ts.isIdentifier(node)&&['WebSocketPair','HTMLRewriter','passThroughOnException','timingSafeEqual'].includes(node.text))fail(node.text);
28
+ if(ts.isIdentifier(node)&&(['WebSocketPair','passThroughOnException','timingSafeEqual'].includes(node.text)||(node.text==='HTMLRewriter'&&engine!=='workerd')))fail(node.text);
29
29
  if(ts.isCallExpression(node)&&ts.isIdentifier(node.expression)&&node.expression.text==='email'&&!localNames.has('email'))fail('email()');
30
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
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));
@@ -23,6 +23,15 @@ it with these files and the seed's container image folder (workerd engine) to
23
23
  container that stops by itself ends its demo too.
24
24
  - `capacity.mjs`: `DemoCapacity` admits at most `max_instances` live demos.
25
25
  - `pages.mjs`: the start and ended pages (12ui designs), strict CSP.
26
+ - `remove.mjs`: `rer deploy --demo --remove --yes`. The deploy passes the
27
+ demo's record (`plan.record`) to `wrangler deploy --message`; removal takes
28
+ the Worker for the demo's only while it serves that version, the Custom
29
+ Domain only while it routes to that Worker and the Container application
30
+ only while it belongs to that Worker's DemoContainer namespace, refuses
31
+ anything else before the first delete, deletes by exact id (the Worker
32
+ last) and reads back that each is gone (export/DEMO.md "Removing a hosted
33
+ demo"). `cli/demo-remove.test.mjs` runs it through the CLI against a fake
34
+ Cloudflare account (`tests/demo-account.mjs`).
26
35
 
27
36
  `node --test modules/demo-host/tests/*.test.mjs` runs the Worker in workerd
28
37
  with its real Durable Objects and rate limit; Turnstile and the container
@@ -1,5 +1,5 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { assert, resourceName } from '../deploy-kit/validation.mjs';
2
+ import { assert, hash, resourceName } from '../deploy-kit/validation.mjs';
3
3
  import { ownerWorkerName } from '../deploy-kit/owner.mjs';
4
4
  import { siteDeclaration } from '../deploy-kit/site.mjs';
5
5
 
@@ -34,7 +34,7 @@ export function demoDeclaration(value, originVar) {
34
34
  export function demoPlan({ project, environment, compatibilityDate, originVar, declaration, turnstileSiteKey }) {
35
35
  assert(/^\d{4}-\d{2}-\d{2}$/.test(compatibilityDate ?? '') && /^[A-Z][A-Z0-9_]{0,63}$/.test(originVar ?? ''), 'invalid-plan');
36
36
  const { domain, name, maxInstances, settings } = demoDeclaration(declaration, originVar);
37
- const worker = `${ownerWorkerName(project, environment)}--demo`, hostname = `demo.${domain}`;
37
+ const worker = `${ownerWorkerName(project, environment)}--demo`, hostname = `demo.${domain}`, container = worker.replace(/-+/g, '-');
38
38
  assert(resourceName(worker), 'owner-name-too-long');
39
39
  // Rate limit namespaces are account-wide integers: one per demo Worker.
40
40
  const namespace = String(1000 + parseInt(createHash('sha256').update(worker).digest('hex').slice(0, 8), 16) % 1_000_000_000);
@@ -46,8 +46,13 @@ export function demoPlan({ project, environment, compatibilityDate, originVar, d
46
46
  ...(turnstileSiteKey ? { TURNSTILE_SITE_KEY: turnstileSiteKey } : {}) },
47
47
  durable_objects: { bindings: [{ name: 'DEMO', class_name: 'DemoContainer' }, { name: 'CAPACITY', class_name: 'DemoCapacity' }] },
48
48
  migrations: [{ tag: 'v1', new_sqlite_classes: ['DemoContainer', 'DemoCapacity'] }],
49
- containers: [{ name: worker.replace(/-+/g, '-'), class_name: 'DemoContainer', image: './image/Dockerfile', max_instances: maxInstances, instance_type: 'basic' }],
49
+ containers: [{ name: container, class_name: 'DemoContainer', image: './image/Dockerfile', max_instances: maxInstances, instance_type: 'basic' }],
50
50
  ratelimits: [{ name: 'STARTS', namespace_id: namespace, simple: { limit: 3, period: 60 } }],
51
51
  };
52
- return { worker, hostname, origin: `https://${hostname}`, maxInstances, settings: Object.keys(settings), wrangler };
52
+ return { worker, hostname, container, record: demoRecord({ worker, hostname, container }), origin: `https://${hostname}`, maxInstances, settings: Object.keys(settings), wrangler };
53
53
  }
54
+
55
+ /** The demo's record of what `rer deploy --demo` creates, kept on the provider so a
56
+ * fresh checkout (a CI runner) can remove it: the deploy writes it as the Worker
57
+ * version's message, and only a Worker serving it is taken for the demo's own. */
58
+ export const demoRecord = ({ worker, hostname, container }) => `rer-demo:${hash({ worker, hostname, container })}`;
@@ -0,0 +1,67 @@
1
+ import { assert } from '../deploy-kit/validation.mjs';
2
+ import { workerSettings } from '../deploy-kit/owner.mjs';
3
+ import { servedVersion } from '../deploy-kit/site.mjs';
4
+ import { deleteWorker } from '../deploy-kit/teardown.mjs';
5
+
6
+ /* `rer deploy --demo --remove --yes`: remove the hosted demo `rer deploy --demo`
7
+ * made for this environment, by exact provider ids, and nothing else. What the
8
+ * deploy made: the front Worker (its Durable Object namespaces go with it), the
9
+ * Workers Custom Domain demo.<domain> (Cloudflare adds and removes its DNS
10
+ * record with it) and the Container application `wrangler deploy` created for
11
+ * the Worker's DemoContainer namespace. It makes no D1, KV, R2, queue or DNS
12
+ * record of its own: the domain's record is Cloudflare's, and goes with it.
13
+ *
14
+ * The Worker is the demo's own only while it serves the version carrying the
15
+ * demo's record (plan.mjs `demoRecord`). The domain is the demo's only while it
16
+ * routes to that Worker, the Container application only while it belongs to
17
+ * that Worker's DemoContainer namespace. Anything else of those names, or
18
+ * attached to that Worker, is refused before the first delete. The Worker goes
19
+ * last, so a run cut short leaves the record for the next one; once everything
20
+ * is gone a second run is a no-op. */
21
+
22
+ function refuse(code, resource) { const error = new Error(code); error.resource = resource; return error; }
23
+ const rows = value => { assert(Array.isArray(value), 'provider-invalid-list'); return value; };
24
+
25
+ /** What exists of the demo now, each with its exact id; refuses whatever is not provably the demo's. */
26
+ async function inventory(api, plan) {
27
+ const named = rows(await api.request(`/workers/domains?hostname=${plan.hostname}`)).filter(row => row?.hostname === plan.hostname);
28
+ const attached = rows(await api.request(`/workers/domains?service=${plan.worker}`)).filter(row => row?.service === plan.worker);
29
+ const apps = rows(await api.request('/containers/applications')).filter(row => row?.name === plan.container);
30
+ const namespaces = rows(await api.list('/workers/durable_objects/namespaces')).filter(row => row?.script === plan.worker);
31
+ const worker = await workerSettings(api, plan.worker) !== null;
32
+ for (const row of named) if (row.service !== plan.worker) throw refuse('resource-name-collision', `domain:${plan.hostname}`);
33
+ if (worker) {
34
+ const served = await servedVersion(api, plan.worker);
35
+ if (served.annotation !== plan.record) throw refuse('resource-name-collision', `worker:${plan.worker}`);
36
+ if (!served.current) throw refuse('owned-resource-replaced', `worker:${plan.worker}`);
37
+ for (const row of attached) if (row.hostname !== plan.hostname) throw refuse('resource-not-in-record', `domain:${row.hostname}`);
38
+ } else if (named.length || attached.length || apps.length) {
39
+ // Without the Worker nothing proves these are the demo's.
40
+ throw refuse('uncertain-resource-create', named[0] || attached[0] ? `domain:${(named[0] ?? attached[0]).hostname}` : `container:${plan.container}`);
41
+ }
42
+ const container = namespaces.find(row => row.class === 'DemoContainer')?.id;
43
+ for (const app of apps) if (!container || app.durable_objects?.namespace_id !== container) throw refuse('resource-name-collision', `container:${plan.container}`);
44
+ return { worker, domains: named, apps };
45
+ }
46
+
47
+ export async function demoRemove({ api, plan, sleep }) {
48
+ const found = await inventory(api, plan);
49
+ if (!found.worker) return { worker: plan.worker, removed: [], remaining: [], alreadyRemoved: true };
50
+ const removed = [];
51
+ for (const domain of found.domains) {
52
+ await api.request(`/workers/domains/${domain.id}`, { method: 'DELETE' });
53
+ removed.push(`domain:${plan.hostname}`);
54
+ }
55
+ for (const app of found.apps) { await api.request(`/containers/applications/${app.id}`, { method: 'DELETE' }); removed.push(`container:${plan.container}`); }
56
+ await deleteWorker({ api, worker: plan.worker, ...sleep ? { sleep } : {} });
57
+ removed.push(`worker:${plan.worker}`);
58
+ // Read back: nothing of the demo is listed any more.
59
+ const remaining = [];
60
+ if (await workerSettings(api, plan.worker) !== null) remaining.push(`worker:${plan.worker}`);
61
+ for (const row of rows(await api.list('/workers/durable_objects/namespaces'))) if (row?.script === plan.worker) remaining.push(`durable-object:${row.class}`);
62
+ if (rows(await api.request(`/workers/domains?hostname=${plan.hostname}`)).some(row => row?.hostname === plan.hostname)) remaining.push(`domain:${plan.hostname}`);
63
+ const apps = rows(await api.request('/containers/applications'));
64
+ for (const app of found.apps) if (apps.some(row => row?.id === app.id)) remaining.push(`container:${plan.container}`);
65
+ if (remaining.length) { const error = new Error('remove-incomplete'); error.remaining = remaining; error.removed = removed.filter(item => !remaining.includes(item)); throw error; }
66
+ return { worker: plan.worker, removed, remaining: [] };
67
+ }
@@ -22,6 +22,9 @@ export async function* r2ObjectPages(api, bucket) {
22
22
  const data = await api.envelope(`/r2/buckets/${bucket}/objects?per_page=1000${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ''}`);
23
23
  const rows = data.result, info = data.result_info;
24
24
  assert(Array.isArray(rows) && rows.length <= 1000 && rows.every(row => typeof row?.key === 'string' && row.key.length), 'invalid-r2-object-list');
25
+ // Empty object listings may omit pagination or return null. Only that
26
+ // shape proves completion without explicit pagination evidence.
27
+ if (rows.length === 0 && info == null) { yield rows; return; }
25
28
  assert(info && typeof info.is_truncated === 'boolean' && (!info.delimited || Array.isArray(info.delimited) && !info.delimited.length), 'provider-incomplete-pagination');
26
29
  assert(new Set(rows.map(row => row.key)).size === rows.length, 'invalid-r2-object-list');
27
30
  if (info.is_truncated) {
@@ -66,7 +66,7 @@ export function sitePlan({ project, environment, compatibilityDate, declaration,
66
66
  }
67
67
 
68
68
  /** The version the Worker's latest deployment serves, as the kit reads ownership: null when there is no Worker. */
69
- async function servedVersion(api, worker) {
69
+ export async function servedVersion(api, worker) {
70
70
  if (!await workerSettings(api, worker)) return null;
71
71
  const { deployments } = await api.request(`/workers/scripts/${worker}/deployments`);
72
72
  assert(Array.isArray(deployments) && deployments.length > 0, 'invalid-deployments');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runeditrun/rer",
3
- "version": "0.2.11",
3
+ "version": "0.2.13",
4
4
  "description": "The rer command: install, set up, run and launch Run Edit Run checkouts.",
5
5
  "license": "MIT",
6
6
  "type": "module",