@somewhere-cloud/cli 0.38.88 → 0.38.90

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.
@@ -18,6 +18,9 @@ import { callPlatformTool } from '../lib/platform-tools.js';
18
18
  import { isRecord, unwrapPlatformData } from '../lib/platform-command.js';
19
19
  import { countPublishSurface, formatPublishSurface } from '../lib/surface-counts.js';
20
20
  import { promoteCommandForShell, promoteCommandLines } from '../lib/promote-handoff.js';
21
+ import { hashFiles } from '../lib/base-files.js';
22
+ import { table } from '../lib/output.js';
23
+ import { clearPreviewRecord, decideContinue, formatDuration, loadPreviewRecord, openPreviewsFromStatus, previewIsStale, savePreviewRecord, } from '../lib/preview-record.js';
21
24
  const WATCH_EXTS = /\.(ts|tsx|js|jsx|mjs|html|css|json|svg|md|txt|png|jpe?g|gif|webp|ico|woff2?|ttf|otf)$/i;
22
25
  const DEBOUNCE_MS = 500;
23
26
  const RETRYABLE_DRAFT_CODES = new Set([
@@ -203,11 +206,21 @@ export function previewSessionStateFromDeployment(value, previewSessionId, previ
203
206
  return 'active';
204
207
  }
205
208
  async function readPreviewSessionState(projectId, previewSessionId, previewId) {
209
+ return (await readPreviewSession(projectId, previewSessionId, previewId)).state;
210
+ }
211
+ /** The session's lifecycle state, and whether production has moved past its base. */
212
+ async function readPreviewSession(projectId, previewSessionId, previewId) {
206
213
  try {
207
- return previewSessionStateFromDeployment(await callPlatformTool('deploy_status', { project_id: projectId }, { allTools: true }), previewSessionId, previewId);
214
+ const status = await callPlatformTool('deploy_status', { project_id: projectId }, { allTools: true });
215
+ const open = openPreviewsFromStatus(status);
216
+ const mine = open.previews.find((item) => item.previewSessionId === previewSessionId);
217
+ return {
218
+ state: previewSessionStateFromDeployment(status, previewSessionId, previewId),
219
+ stale: mine ? previewIsStale(mine, open.activeReleaseId) : false,
220
+ };
208
221
  }
209
222
  catch {
210
- return 'unknown';
223
+ return { state: 'unknown', stale: false };
211
224
  }
212
225
  }
213
226
  function previewPollMs() {
@@ -221,29 +234,176 @@ export function registerPreview(program) {
221
234
  + 'reachable only by you until you share the link. The build is the one production would get; '
222
235
  + 'the database starts as a separate copy of your production data, so nothing you try here can '
223
236
  + 'change production rows. Nothing your users see changes — production keeps serving what you last '
224
- + 'promoted, until you run `somewhere promote`. Reach for this when you want the real hosted app in '
225
- + 'front of you, or when your agent reaches the platform over MCP and cannot serve on localhost. '
237
+ + 'promoted, until you promote a preview. Reach for this when you want your change running on the platform '
238
+ + 'against a copy of your data, or when your agent reaches the platform over MCP and cannot serve on localhost. '
239
+ + 'Not available in a preview yet: signing in, public reads for visitors, sw.groups, server user lookup, '
240
+ + 'jobs and cron handlers, and running tests (somewhere docs dev-environments lists them). '
241
+ + 'It continues the preview this folder opened while that is open; --new opens a fresh one. '
226
242
  + 'The plans that include it are listed at https://somewhere.cloud/pricing; '
227
243
  + '`somewhere dev` provides frontend hot reload against the deployed backend.')
228
244
  .option('--project <id>', 'Override project ID')
229
245
  .option('--publish-first', 'For a project that has never been published: publish this directory to production first, so the preview has a live version to build on. Without it you are asked, and a script that cannot be asked is refused.')
230
246
  .option('--json', 'Print a typed JSON refusal when preview cannot start')
231
247
  .option('--once', 'Sync once, print the preview link and promote command, and exit instead of watching')
248
+ .option('--new', 'Open a fresh preview (a new copy of production data) instead of continuing this folder\'s open one')
249
+ // `somewhere preview <typo>` used to ignore the word and open a new preview
250
+ // with a fresh copy of production data; an unknown word is refused instead.
251
+ .allowExcessArguments(false)
232
252
  .action(async (opts) => {
233
253
  await runHotDeploy(opts);
234
254
  });
255
+ preview
256
+ .command('list')
257
+ .description('List open previews with their age and when they close; each holds a copy of production data until promoted, closed or expired')
258
+ .option('--project <id>', 'Override project ID')
259
+ .option('--json', 'Print the previews as JSON')
260
+ .action(async (_opts, cmd) => {
261
+ // `preview` defines --project and --json too and would take them; read both levels.
262
+ const opts = cmd.optsWithGlobals();
263
+ try {
264
+ const projectId = opts.project ?? loadProjectConfig()?.project_id;
265
+ if (!projectId)
266
+ throw new Error('No project linked. Run `somewhere init` or pass --project <id>.');
267
+ const { activeReleaseId, previews } = openPreviewsFromStatus(await callPlatformTool('deploy_status', { project_id: projectId }, { allTools: true }));
268
+ const mine = loadPreviewRecord(process.cwd(), projectId)?.preview_session_id ?? null;
269
+ const now = Date.now();
270
+ const rows = previews.map((item) => ({
271
+ preview_session_id: item.previewSessionId,
272
+ preview_id: item.previewId,
273
+ created_at: item.createdAt,
274
+ last_updated_at: item.lastUpdatedAt,
275
+ expires_at: item.expiresAt,
276
+ age_seconds: item.createdAt ? Math.round((now - Date.parse(item.createdAt)) / 1000) : null,
277
+ expires_in_seconds: item.expiresAt ? Math.round((Date.parse(item.expiresAt) - now) / 1000) : null,
278
+ promotable: !previewIsStale(item, activeReleaseId),
279
+ this_folder: item.previewSessionId === mine,
280
+ }));
281
+ if (opts.json) {
282
+ printJson({ project_id: projectId, active_release_id: activeReleaseId, previews: rows });
283
+ return;
284
+ }
285
+ if (rows.length === 0) {
286
+ console.log('No open previews. Start one with: somewhere preview');
287
+ return;
288
+ }
289
+ table(['Preview session', 'Preview id', 'Opened', 'Last saved', 'Closes in', 'Promotable', 'Folder'], rows.map((row) => [
290
+ row.preview_session_id,
291
+ row.preview_id,
292
+ row.age_seconds === null ? '—' : `${formatDuration(row.age_seconds * 1000)} ago`,
293
+ row.last_updated_at ? `${formatDuration(now - Date.parse(row.last_updated_at))} ago` : '—',
294
+ row.expires_in_seconds === null ? '—' : formatDuration(row.expires_in_seconds * 1000),
295
+ row.promotable ? 'yes' : 'no: production changed',
296
+ row.this_folder ? 'this folder' : '',
297
+ ]));
298
+ console.log(dim('Each open preview holds a copy of production data until it is promoted, closed, or unused for 24 h (7 days at most).'));
299
+ console.log(dim('Close one: somewhere preview close <preview_session_id>. Promote one: somewhere promote <preview_session_id> <preview_id>.'));
300
+ }
301
+ catch (err) {
302
+ if (opts.json)
303
+ printJsonError(typedErrorCode(err) ?? 'PREVIEW_LIST_FAILED', err instanceof Error ? err.message : String(err));
304
+ else
305
+ error(err instanceof Error ? err.message : String(err), err);
306
+ process.exitCode = 1;
307
+ }
308
+ });
309
+ preview
310
+ .command('close [preview_session_id]')
311
+ .description('Close a preview and delete its copy of production data and files (default: this folder\'s open preview)')
312
+ .option('--project <id>', 'Override project ID')
313
+ .option('--all', 'Close every open preview of the project')
314
+ .option('--json', 'Print the result as JSON')
315
+ .action(async (previewSessionId, _opts, cmd) => {
316
+ const opts = cmd.optsWithGlobals();
317
+ try {
318
+ const projectId = opts.project ?? loadProjectConfig()?.project_id;
319
+ if (!projectId)
320
+ throw new Error('No project linked. Run `somewhere init` or pass --project <id>.');
321
+ if (opts.all && previewSessionId)
322
+ throw new Error('Pass a preview_session_id or --all, not both.');
323
+ const { previews } = openPreviewsFromStatus(await callPlatformTool('deploy_status', { project_id: projectId }, { allTools: true }));
324
+ const recorded = loadPreviewRecord(process.cwd(), projectId);
325
+ let targets;
326
+ if (opts.all)
327
+ targets = previews.map((item) => item.previewSessionId);
328
+ else if (previewSessionId)
329
+ targets = [previewSessionId];
330
+ else if (recorded && previews.some((item) => item.previewSessionId === recorded.preview_session_id))
331
+ targets = [recorded.preview_session_id];
332
+ else if (previews.length === 1)
333
+ targets = [previews[0].previewSessionId];
334
+ else if (previews.length === 0)
335
+ throw new Error('No open preview for this project; nothing was closed.');
336
+ else
337
+ throw new Error(`${previews.length} previews are open and this folder has none of its own; name one, or pass --all: ${previews.map((item) => item.previewSessionId).join(', ')}. Nothing was closed.`);
338
+ if (targets.length === 0) {
339
+ if (opts.json)
340
+ printJson({ project_id: projectId, closed: [] });
341
+ else
342
+ console.log('No open previews; nothing was closed.');
343
+ return;
344
+ }
345
+ const client = new ApiClient(getToken());
346
+ const results = [];
347
+ let failed = false;
348
+ for (const id of targets) {
349
+ try {
350
+ const res = await client.call('POST', '/deploy/preview/close', { project_id: projectId, preview_session_id: id });
351
+ const deleted = res?.cleanup_complete === true;
352
+ results.push({ preview_session_id: id, status: res?.status ?? 'closed', data_deleted: deleted });
353
+ if (recorded?.preview_session_id === id)
354
+ clearPreviewRecord(process.cwd());
355
+ if (opts.json)
356
+ continue;
357
+ if (deleted)
358
+ success(`Closed preview ${id}. Its copy of the production data and files was deleted.`);
359
+ else {
360
+ failed = true;
361
+ warn(`Closed preview ${id}, but deleting its copy of the production data has not finished. Run the same close again to finish it: somewhere preview close ${id}`);
362
+ }
363
+ }
364
+ catch (err) {
365
+ failed = true;
366
+ const code = typedErrorCode(err);
367
+ results.push({ preview_session_id: id, status: code ?? 'error', data_deleted: false });
368
+ if (!opts.json) {
369
+ error(`Preview ${id} was not closed: ${err instanceof Error ? err.message : String(err)}`, err);
370
+ if (code === 'DRAFT_NOT_FOUND')
371
+ info('`somewhere preview list` shows the open previews.');
372
+ }
373
+ }
374
+ }
375
+ if (opts.json)
376
+ printJson({ project_id: projectId, closed: results });
377
+ if (failed)
378
+ process.exitCode = 1;
379
+ }
380
+ catch (err) {
381
+ if (opts.json)
382
+ printJsonError(typedErrorCode(err) ?? 'PREVIEW_CLOSE_FAILED', err instanceof Error ? err.message : String(err));
383
+ else
384
+ error(err instanceof Error ? err.message : String(err), err);
385
+ process.exitCode = 1;
386
+ }
387
+ });
235
388
  preview
236
389
  .command('link')
237
390
  .description('Mint a fresh single-use link to the open preview (each link works once)')
238
391
  .option('--project <id>', 'Override project ID')
239
392
  .option('--preview-session <id>', 'Which preview, when more than one is open (its preview_session_id)')
240
393
  .option('--json', 'Print { url, preview_session_id, preview_id } as JSON')
241
- .action(async (opts) => {
394
+ .action(async (_opts, cmd) => {
395
+ // `preview` also defines --project and --json, and Commander gives them to
396
+ // the parent; optsWithGlobals reads them wherever they were parsed.
397
+ const opts = cmd.optsWithGlobals();
242
398
  try {
243
399
  const projectId = opts.project ?? loadProjectConfig()?.project_id;
244
400
  if (!projectId)
245
401
  throw new Error('No project linked. Run `somewhere init` or pass --project <id>.');
246
- const candidate = choosePreviewCandidate(await callPlatformTool('deploy_status', { project_id: projectId }, { allTools: true }), opts.previewSession);
402
+ const status = await callPlatformTool('deploy_status', { project_id: projectId }, { allTools: true });
403
+ // Without a choice, this folder's own open preview is the one meant.
404
+ const folderPreview = loadPreviewRecord(process.cwd(), projectId)?.preview_session_id;
405
+ const folderOpen = folderPreview && openPreviewsFromStatus(status).previews.some((item) => item.previewSessionId === folderPreview);
406
+ const candidate = choosePreviewCandidate(status, opts.previewSession ?? (folderOpen ? folderPreview : undefined));
247
407
  const handoff = await mintPreviewHandoff(new ApiClient(getToken()), projectId, candidate.draftId, candidate.candidateReleaseId);
248
408
  if (opts.json) {
249
409
  printJson({
@@ -258,7 +418,10 @@ export function registerPreview(program) {
258
418
  console.log(dim(' This link works once; run `somewhere preview link` again for another.'));
259
419
  }
260
420
  catch (err) {
261
- error(err instanceof Error ? err.message : String(err), err);
421
+ if (opts.json)
422
+ printJsonError(typedErrorCode(err) ?? 'PREVIEW_LINK_FAILED', err instanceof Error ? err.message : String(err));
423
+ else
424
+ error(err instanceof Error ? err.message : String(err), err);
262
425
  process.exitCode = 1;
263
426
  }
264
427
  });
@@ -267,16 +430,8 @@ export function registerPreview(program) {
267
430
  * caller named, or the only open one. Several open previews and no choice is
268
431
  * an error that lists them, never a guess. */
269
432
  export function choosePreviewCandidate(status, previewSessionId) {
270
- const deployment = unwrapPlatformData(status);
271
- const open = (isRecord(deployment) && Array.isArray(deployment.preview_candidates)
272
- ? deployment.preview_candidates.filter(isRecord)
273
- : []).flatMap((item) => {
274
- const draftId = typeof item.preview_session_id === 'string' ? item.preview_session_id : item.draft_id;
275
- const candidateReleaseId = typeof item.preview_id === 'string' ? item.preview_id : item.candidate_release_id;
276
- return typeof draftId === 'string' && typeof candidateReleaseId === 'string'
277
- ? [{ draftId, candidateReleaseId }]
278
- : [];
279
- });
433
+ const open = openPreviewsFromStatus(status).previews
434
+ .map((item) => ({ draftId: item.previewSessionId, candidateReleaseId: item.previewId }));
280
435
  if (previewSessionId) {
281
436
  const match = open.find((item) => item.draftId === previewSessionId);
282
437
  if (!match)
@@ -459,6 +614,22 @@ export class SourceBaseRequiredError extends Error {
459
614
  this.name = 'SourceBaseRequiredError';
460
615
  }
461
616
  }
617
+ /** The folder's source was read from a production version that is no longer
618
+ * live. The platform refuses that snapshot (STALE_RELEASE_BASE) only after
619
+ * uploading and building it; the folder already knows, so say it first. */
620
+ export class SourceBaseStaleError extends Error {
621
+ baseReleaseId;
622
+ activeReleaseId;
623
+ code = 'STALE_RELEASE_BASE';
624
+ constructor(baseReleaseId, activeReleaseId) {
625
+ super('Production changed since this folder was last pulled or deployed, so a new preview cannot start from it. '
626
+ + 'Nothing was uploaded. Next: run `somewhere pull` (it keeps your edits and stops if a file changed both here '
627
+ + 'and live), then `somewhere preview` again.');
628
+ this.baseReleaseId = baseReleaseId;
629
+ this.activeReleaseId = activeReleaseId;
630
+ this.name = 'SourceBaseStaleError';
631
+ }
632
+ }
462
633
  export class FirstPublishReleaseUnknownError extends Error {
463
634
  code = 'PUBLISHED_RELEASE_UNKNOWN';
464
635
  constructor() {
@@ -477,6 +648,9 @@ export async function resolveBaseRelease(args) {
477
648
  if (!args.sourceBase)
478
649
  throw new SourceBaseRequiredError();
479
650
  if (args.sourceBase.releaseId) {
651
+ if (state.activeReleaseId && args.sourceBase.releaseId !== state.activeReleaseId) {
652
+ throw new SourceBaseStaleError(args.sourceBase.releaseId, state.activeReleaseId);
653
+ }
480
654
  return { baseReleaseId: args.sourceBase.releaseId, published: false };
481
655
  }
482
656
  if (state.activeReleaseId)
@@ -551,101 +725,149 @@ async function runHotDeploy(opts) {
551
725
  }
552
726
  await showProjectNotices(client, projectId);
553
727
  const { files, binaryFiles, functions } = collected;
554
- const draftId = `draft_${randomUUID()}`;
555
728
  const firstOperationId = `previewop_${randomUUID()}`;
556
729
  const showPublishProgress = opts.publishFirst === true && opts.json !== true;
557
730
  const phase = (label, operation) => showPublishProgress ? runPreviewPhase(label, operation) : operation();
731
+ const say = opts.json ? () => { } : info;
732
+ // One preview per folder: continue the one this folder opened while it is
733
+ // open and still promotable, instead of copying production again.
734
+ const recorded = loadPreviewRecord(cwd, projectId);
735
+ let openNow = { activeReleaseId: null, previews: [] };
736
+ if (recorded || !opts.new) {
737
+ try {
738
+ openNow = openPreviewsFromStatus(await callPlatformTool('deploy_status', { project_id: projectId }, { allTools: true }));
739
+ }
740
+ catch {
741
+ // Unreadable: a new preview is opened below, and its own checks refuse loudly.
742
+ }
743
+ }
744
+ const decision = decideContinue({
745
+ recorded, open: openNow.previews, activeReleaseId: openNow.activeReleaseId, forceNew: opts.new === true,
746
+ });
747
+ let draftId;
748
+ let expectedPreviewId;
749
+ if (decision.action === 'continue') {
750
+ draftId = decision.preview.previewSessionId;
751
+ expectedPreviewId = decision.preview.previewId;
752
+ const when = [];
753
+ if (decision.preview.createdAt)
754
+ when.push(`opened ${formatDuration(Date.now() - Date.parse(decision.preview.createdAt))} ago`);
755
+ if (decision.preview.expiresAt)
756
+ when.push(`closes in ${formatDuration(Date.parse(decision.preview.expiresAt) - Date.now())} if unused`);
757
+ say(`Continuing this folder's preview ${draftId}${when.length ? ` (${when.join(', ')})` : ''}.`);
758
+ say('Pass --new to open a fresh preview with a new copy of production data instead.');
759
+ }
760
+ else {
761
+ draftId = `draft_${randomUUID()}`;
762
+ expectedPreviewId = null;
763
+ if (decision.reason === 'stale') {
764
+ if (!opts.json) {
765
+ warn(`This folder's preview ${decision.recorded.preview_session_id} was opened from an older production version, so it can no longer be promoted. Opening a new one.`);
766
+ info(`It still holds a copy of production data until it expires; close it with: somewhere preview close ${decision.recorded.preview_session_id}`);
767
+ }
768
+ }
769
+ else if (decision.reason === 'not-open') {
770
+ say(`This folder's last preview ${decision.recorded.preview_session_id} is no longer open; opening a new one.`);
771
+ clearPreviewRecord(cwd);
772
+ }
773
+ else if (decision.reason === 'none-recorded' && openNow.previews.length > 0) {
774
+ say(`${openNow.previews.length} other preview${openNow.previews.length === 1 ? ' is' : 's are'} open for this project (somewhere preview list). Opening a new one for this folder.`);
775
+ }
776
+ }
558
777
  // The first preview snapshot must name the production release it was read
559
778
  // from (base_release_id) — the platform binds the preview to that exact
560
779
  // source release. Everything about how that id is obtained, including
561
- // the refusal to invent one, lives in resolveBaseRelease.
562
- let baseReleaseId;
563
- try {
564
- const resolved = await resolveBaseRelease({
565
- sourceBase: readSourceBase(loadProjectConfig(cwd), projectId),
566
- cloudDevAllowed: () => phase('Checking preview access', () => readCloudDevAllowed(projectId)),
567
- readBaseReleaseState: () => phase('Checking the production release', () => readBaseReleaseState(projectId)),
568
- confirmPublish: () => readPublishConsent(opts.publishFirst === true),
569
- announce: opts.json ? () => { } : info,
570
- publish: async () => {
571
- const result = await phase('Publishing the first production version', () => callDraftCandidate(client, '/deploy', {
572
- project_id: projectId,
573
- scope: 'all',
574
- base_release_id: null,
575
- files,
576
- binary_files: binaryFiles,
577
- functions,
578
- replace_functions: true,
579
- }, (retryError) => {
580
- info(`Publish attempt ended with ${previewPlatformState(retryError)}; retrying the same operation once.`);
581
- }));
582
- const releaseId = result.active_release_id ?? result.release_id;
583
- if (releaseId?.trim())
584
- saveSourceBase(cwd, projectId, releaseId);
585
- return releaseId;
586
- },
587
- });
588
- baseReleaseId = resolved.baseReleaseId;
589
- if (resolved.published)
590
- success('Published — this project now has a live version.');
591
- }
592
- catch (err) {
593
- // A completed publish with an unnamed release needs truthful recovery copy;
594
- // refusal paths below must not claim that anything was published.
595
- if (err instanceof SourceBaseRequiredError || err instanceof FirstPublishReleaseUnknownError) {
596
- if (opts.json)
597
- printJsonError(err.code, err.message);
598
- else
599
- error(err.message);
600
- process.exit(1);
601
- }
602
- if (err instanceof CloudDevUnavailableError) {
603
- const message = cloudDevUnavailableMessage(await readPreviewPlanNames(client));
604
- if (opts.json) {
605
- printJsonError(err.code, message);
606
- process.exit(1);
607
- }
608
- error(message);
609
- info('Nothing was created or changed — whatever is live stays live.');
610
- info('`somewhere deploy` publishes to production on any plan, and `somewhere dev` runs the same app on your machine.');
611
- process.exit(1);
780
+ // the refusal to invent one, lives in resolveBaseRelease. A continued
781
+ // preview already has its base.
782
+ let baseReleaseId = null;
783
+ if (expectedPreviewId === null)
784
+ try {
785
+ const resolved = await resolveBaseRelease({
786
+ sourceBase: readSourceBase(loadProjectConfig(cwd), projectId),
787
+ cloudDevAllowed: () => phase('Checking preview access', () => readCloudDevAllowed(projectId)),
788
+ readBaseReleaseState: () => phase('Checking the production release', () => readBaseReleaseState(projectId)),
789
+ confirmPublish: () => readPublishConsent(opts.publishFirst === true),
790
+ announce: opts.json ? () => { } : info,
791
+ publish: async () => {
792
+ const result = await phase('Publishing the first production version', () => callDraftCandidate(client, '/deploy', {
793
+ project_id: projectId,
794
+ scope: 'all',
795
+ base_release_id: null,
796
+ files,
797
+ binary_files: binaryFiles,
798
+ functions,
799
+ replace_functions: true,
800
+ }, (retryError) => {
801
+ info(`Publish attempt ended with ${previewPlatformState(retryError)}; retrying the same operation once.`);
802
+ }));
803
+ const releaseId = result.active_release_id ?? result.release_id;
804
+ if (releaseId?.trim())
805
+ saveSourceBase(cwd, projectId, releaseId);
806
+ return releaseId;
807
+ },
808
+ });
809
+ baseReleaseId = resolved.baseReleaseId;
810
+ if (resolved.published)
811
+ success('Published — this project now has a live version.');
612
812
  }
613
- if (err instanceof BaseReleaseUnknownError) {
614
- if (err.code === 'PROJECT_NOT_FOUND') {
813
+ catch (err) {
814
+ // A completed publish with an unnamed release needs truthful recovery copy;
815
+ // refusal paths below must not claim that anything was published.
816
+ if (err instanceof SourceBaseRequiredError || err instanceof FirstPublishReleaseUnknownError
817
+ || err instanceof SourceBaseStaleError) {
615
818
  if (opts.json)
616
819
  printJsonError(err.code, err.message);
617
820
  else
618
- error(`${err.code}: ${err.message}`);
821
+ error(err.message);
619
822
  process.exit(1);
620
823
  }
621
- error(err.message);
622
- info('Nothing was created or changed — whatever is live stays live.');
623
- info('Try `somewhere preview` again. To publish this directory to production deliberately, run `somewhere deploy`.');
624
- process.exit(1);
625
- }
626
- if (err instanceof PublishConsentRequiredError) {
627
- if (opts.json) {
628
- printJsonError(err.code, err.why === 'declined'
629
- ? 'Publishing the first production version was declined. Nothing was created or changed.'
630
- : 'This project has never been published, so a preview has no live version to build on. Re-run with --publish-first to publish deliberately. Nothing was created or changed.');
824
+ if (err instanceof CloudDevUnavailableError) {
825
+ const message = cloudDevUnavailableMessage(await readPreviewPlanNames(client));
826
+ if (opts.json) {
827
+ printJsonError(err.code, message);
828
+ process.exit(1);
829
+ }
830
+ error(message);
831
+ info('Nothing was created or changed — whatever is live stays live.');
832
+ info('`somewhere deploy` publishes to production on any plan, and `somewhere dev` runs the same app on your machine.');
631
833
  process.exit(1);
632
834
  }
633
- if (err.why === 'declined') {
634
- warn('Nothing was published — whatever is live stays live.');
635
- }
636
- else {
637
- error('This project has never been published, so a preview has no live version to build on.');
638
- info('Re-run as `somewhere preview --publish-first` to publish this directory to production first, or run `somewhere deploy` yourself.');
835
+ if (err instanceof BaseReleaseUnknownError) {
836
+ if (err.code === 'PROJECT_NOT_FOUND') {
837
+ if (opts.json)
838
+ printJsonError(err.code, err.message);
839
+ else
840
+ error(`${err.code}: ${err.message}`);
841
+ process.exit(1);
842
+ }
843
+ error(err.message);
639
844
  info('Nothing was created or changed — whatever is live stays live.');
845
+ info('Try `somewhere preview` again. To publish this directory to production deliberately, run `somewhere deploy`.');
846
+ process.exit(1);
847
+ }
848
+ if (err instanceof PublishConsentRequiredError) {
849
+ if (opts.json) {
850
+ printJsonError(err.code, err.why === 'declined'
851
+ ? 'Publishing the first production version was declined. Nothing was created or changed.'
852
+ : 'This project has never been published, so a preview has no live version to build on. Re-run with --publish-first to publish deliberately. Nothing was created or changed.');
853
+ process.exit(1);
854
+ }
855
+ if (err.why === 'declined') {
856
+ warn('Nothing was published — whatever is live stays live.');
857
+ }
858
+ else {
859
+ error('This project has never been published, so a preview has no live version to build on.');
860
+ info('Re-run as `somewhere preview --publish-first` to publish this directory to production first, or run `somewhere deploy` yourself.');
861
+ info('Nothing was created or changed — whatever is live stays live.');
862
+ }
863
+ process.exit(1);
640
864
  }
865
+ if (!(isBuildError(err) && renderBuildError(err, cwd))) {
866
+ error(err instanceof Error ? err.message : String(err), err);
867
+ }
868
+ error('Could not publish the first version, so the private preview has nothing to build on.');
641
869
  process.exit(1);
642
870
  }
643
- if (!(isBuildError(err) && renderBuildError(err, cwd))) {
644
- error(err instanceof Error ? err.message : String(err), err);
645
- }
646
- error('Could not publish the first version, so the private preview has nothing to build on.');
647
- process.exit(1);
648
- }
649
871
  // Initial full sync to the PREVIEW slot (preview: true). Writes only the
650
872
  // owner-gated dev slot — never prod, never a version bump or history entry.
651
873
  // /deploy/patch rejects projects with no prior deploy, so a full (preview)
@@ -668,8 +890,8 @@ async function runHotDeploy(opts) {
668
890
  preview: true,
669
891
  preview_session_id: draftId,
670
892
  preview_operation_id: firstOperationId,
671
- expected_preview_id: null,
672
- base_release_id: baseReleaseId,
893
+ expected_preview_id: expectedPreviewId,
894
+ ...(baseReleaseId !== null ? { base_release_id: baseReleaseId } : {}),
673
895
  };
674
896
  const res = await phase('Syncing the first private preview', () => callDraftCandidate(client, '/deploy', body, (retryError) => {
675
897
  info(`Preview sync ended with ${previewPlatformState(retryError)}; retrying the same operation once.`);
@@ -686,6 +908,14 @@ async function runHotDeploy(opts) {
686
908
  // two lines above and break the moment the platform returns only the
687
909
  // canonical preview_id.
688
910
  candidateReleaseId = returnedPreviewId;
911
+ // This folder's preview, with its files exactly as sent: the next
912
+ // `somewhere preview` continues it, and promoting it moves the folder's base.
913
+ savePreviewRecord(cwd, {
914
+ project_id: projectId,
915
+ preview_session_id: draftId,
916
+ preview_id: candidateReleaseId,
917
+ files: hashFiles(cwd, collected.published),
918
+ });
689
919
  // Keep the printed capability usable: auto-open consumes a one-time token,
690
920
  // so mint a separate token for the browser before minting the handoff shown
691
921
  // in the terminal.
@@ -697,6 +927,8 @@ async function runHotDeploy(opts) {
697
927
  // number and then a later line counted it separately, so one project
698
928
  // reported three different sizes of itself.
699
929
  success(`Synced ${formatPublishSurface(countPublishSurface({ files, binaryFiles, functions }))} to preview`);
930
+ if (expectedPreviewId === null)
931
+ say(`Opened preview ${draftId} for this folder; \`somewhere preview\` continues it until it is promoted, closed or expires.`);
700
932
  if (res.warnings?.length)
701
933
  for (const w of res.warnings)
702
934
  warn(w);
@@ -706,6 +938,13 @@ async function runHotDeploy(opts) {
706
938
  if (!(isBuildError(err) && renderBuildError(err, cwd))) {
707
939
  error(err instanceof Error ? err.message : String(err), err);
708
940
  }
941
+ const code = typedErrorCode(err);
942
+ if (code === 'STALE_RELEASE_BASE') {
943
+ info('Next: run `somewhere pull` (it keeps your edits), then `somewhere preview` again.');
944
+ }
945
+ else if (expectedPreviewId !== null && code && ['DRAFT_SESSION_TERMINAL', 'DRAFT_CANDIDATE_CONFLICT', 'DRAFT_VERSION_MISMATCH', 'DRAFT_NOT_FOUND'].includes(code)) {
946
+ info(`Preview ${draftId} cannot take this save. Next: \`somewhere preview --new\` opens a fresh preview.`);
947
+ }
709
948
  process.exit(1);
710
949
  }
711
950
  if (opts.once) {
@@ -838,12 +1077,19 @@ async function runHotDeploy(opts) {
838
1077
  schedule();
839
1078
  };
840
1079
  watcher.on('add', onChange).on('change', onChange).on('unlink', onUnlink);
1080
+ let staleWarned = false;
841
1081
  const pollSession = async () => {
842
1082
  if (previewEnded || deploying || pollingSession)
843
1083
  return;
844
1084
  pollingSession = true;
845
1085
  try {
846
- const state = await readPreviewSessionState(projectId, draftId, candidateReleaseId);
1086
+ const { state, stale } = await readPreviewSession(projectId, draftId, candidateReleaseId);
1087
+ if (stale && !staleWarned) {
1088
+ staleWarned = true;
1089
+ console.log('');
1090
+ warn('Production changed since this preview opened (a deploy, promote or rollback), so this preview can no longer be promoted. Saves still update it for review.');
1091
+ info(`To ship these edits: stop here (Ctrl-C), run ${teal('somewhere pull')} (it keeps your edits), then ${teal('somewhere preview')}; it opens a fresh preview. Close this one with ${teal(`somewhere preview close ${draftId}`)}.`);
1092
+ }
847
1093
  if (state === 'active') {
848
1094
  observedSessionActive = true;
849
1095
  return;
@@ -969,6 +1215,17 @@ async function deployBatch(client, projectId, cwd, changed, deleted, draftId, ex
969
1215
  else {
970
1216
  console.log(`${dim(stamp())} ${label} ${green('✓ preview')} ${dim(`(${secs}s)`)}`);
971
1217
  }
1218
+ // Keep this folder's record equal to what the preview now holds.
1219
+ const record = loadPreviewRecord(cwd, projectId);
1220
+ if (record && record.preview_session_id === draftId) {
1221
+ const nextFiles = { ...record.files };
1222
+ for (const rel of deleted)
1223
+ delete nextFiles[rel];
1224
+ for (const rel of changed)
1225
+ if (existsSync(join(cwd, rel)))
1226
+ Object.assign(nextFiles, hashFiles(cwd, [rel]));
1227
+ savePreviewRecord(cwd, { ...record, preview_id: nextCandidate, files: nextFiles });
1228
+ }
972
1229
  try {
973
1230
  const handoff = await mintPreviewHandoff(client, projectId, draftId, nextCandidate);
974
1231
  printPreviewHandoff(handoff);