@sequenceholdings/studio-cli 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +3 -2
  2. package/dist/access/custom-role-hosts.js +8 -6
  3. package/dist/app/manifest-validation.js +4 -2
  4. package/dist/app/manifest.d.ts +2 -0
  5. package/dist/app/manifest.js +2 -0
  6. package/dist/app/paths.js +3 -0
  7. package/dist/app-preview/bundle-dependencies.d.ts +52 -0
  8. package/dist/app-preview/bundle-dependencies.js +121 -0
  9. package/dist/app-preview/commands.d.ts +2 -5
  10. package/dist/app-preview/commands.js +57 -62
  11. package/dist/app-preview/fork-setup.d.ts +66 -0
  12. package/dist/app-preview/fork-setup.js +123 -0
  13. package/dist/app-preview/fork.d.ts +171 -0
  14. package/dist/app-preview/fork.js +279 -0
  15. package/dist/app-preview/install.d.ts +23 -2
  16. package/dist/app-preview/install.js +67 -6
  17. package/dist/app-preview/orm-sdk.d.ts +31 -0
  18. package/dist/app-preview/orm-sdk.js +16 -0
  19. package/dist/app-preview/plan.d.ts +2 -0
  20. package/dist/app-preview/plan.js +2 -2
  21. package/dist/app-preview/report.d.ts +30 -0
  22. package/dist/app-preview/report.js +80 -0
  23. package/dist/app-preview/repository-manifest.d.ts +83 -0
  24. package/dist/app-preview/repository-manifest.js +179 -0
  25. package/dist/app-preview/runners.d.ts +14 -0
  26. package/dist/app-preview/runners.js +83 -23
  27. package/dist/app-preview/session-output.d.ts +5 -0
  28. package/dist/app-preview/session-output.js +28 -0
  29. package/dist/app-preview/source-includes.d.ts +12 -0
  30. package/dist/app-preview/source-includes.js +74 -0
  31. package/dist/app-preview/target.d.ts +8 -0
  32. package/dist/app-preview/target.js +4 -1
  33. package/dist/app-preview/usage.d.ts +7 -0
  34. package/dist/app-preview/usage.js +57 -0
  35. package/dist/envs/commands.js +2 -1
  36. package/dist/login.js +1 -1
  37. package/dist/orm/break-glass.d.ts +15 -0
  38. package/dist/orm/break-glass.js +22 -0
  39. package/dist/orm/delegate.js +10 -8
  40. package/dist/orm/version-guard.d.ts +6 -2
  41. package/dist/orm/version-guard.js +27 -7
  42. package/dist/registry/help.js +5 -6
  43. package/dist/repos/github-init.js +4 -1
  44. package/dist/repos/primitive-declaration.d.ts +27 -0
  45. package/dist/repos/primitive-declaration.js +22 -6
  46. package/dist/repos/seq-ci-release.d.ts +10 -0
  47. package/dist/repos/seq-ci-release.js +27 -0
  48. package/dist/sdk-source.d.ts +15 -0
  49. package/dist/sdk-source.js +30 -11
  50. package/package.json +5 -5
  51. package/release-summary.json +3 -1
package/README.md CHANGED
@@ -3448,6 +3448,7 @@ seq-studio access definitions process <process-id> -e <env>
3448
3448
  seq-studio access list process <process-id> --floor -e <env>
3449
3449
  seq-studio access grant process <process-id> --floor --principal-type service-account --principal-id <account-id> -e <env>
3450
3450
  seq-studio access grant orm <namespace> --key <role> --principal-type group --principal-id <group-id> -e <env>
3451
+ seq-studio access grant application <project-id> --kind runtime --key <role> --principal-type service-account --principal-id <account-id> -e <env>
3451
3452
  seq-studio access revoke orm <namespace> --key <role> --principal-type group --principal-id <group-id> -e <env>
3452
3453
  seq-studio access resolve orm <namespace> -e <env>
3453
3454
  ```
@@ -3480,8 +3481,8 @@ different one unless you pass `--replace`; `revoke` removes only the named tier.
3480
3481
  Grants require grant-management authority on the resource (process editors manage
3481
3482
  Editor/Viewer, process owners every role). Service accounts additionally need you to
3482
3483
  hold `actor` on the account, and take only runtime tiers (`invoker`/`viewer` on a
3483
- process, `invoker` on an agent). You can grant only groups you belong to unless you
3484
- are a platform admin. Service-account grants are Sequence-operator only; managed
3484
+ process, `invoker` on an agent, or a Project runtime role on an application). You can grant only groups you belong to unless you
3485
+ are a platform admin. Granting `actor` or `admin` on the service account itself is Sequence-operator only; managed
3485
3486
  secrets refuse agent sandbox tokens. Roles and pins do not assign users;
3486
3487
  `capabilities.uses` must declare every capability consumed. Fresh previews do not
3487
3488
  register new role keys; activate a release before granting them.
@@ -50,9 +50,9 @@ function applicationKind(flags) {
50
50
  }
51
51
  export const applicationHost = {
52
52
  name: 'application',
53
- summary: 'Application roles (sequence.app.yml schema 3); --kind runtime|collaborator',
53
+ summary: 'Project roles (sequence.app.yml schema 3); --kind runtime|collaborator. Service accounts can hold runtime roles.',
54
54
  singleTier: false,
55
- principals: ['user', 'group', 'organization'],
55
+ principals: ['user', 'group', 'organization', 'service-account'],
56
56
  flags: { kind: 'string' },
57
57
  definitions: (call) => getJson({
58
58
  ...call.request,
@@ -74,9 +74,11 @@ function applicationMutation(call, method) {
74
74
  const { change } = call;
75
75
  if (change.floor || !change.key)
76
76
  throw new Error('Applications have no floor; choose a role with --key <role>.');
77
- if (!applicationHost.principals.includes(change.principal.kind))
78
- throw unsupportedPrincipal(applicationHost, change.principal.kind);
79
- const path = `/api/custom-roles/applications/${encodeURIComponent(call.id)}/grants?kind=${applicationKind(call.flags)}`;
80
- const body = { key: change.key, principal: { type: change.principal.kind, id: change.principal.id } };
77
+ const kind = applicationKind(call.flags);
78
+ if (method === 'grant' && kind === 'collaborator' && change.principal.kind === 'service-account') {
79
+ throw new Error('Service accounts can hold Project runtime roles only. Choose a runtime role with --kind runtime.');
80
+ }
81
+ const path = `/api/custom-roles/applications/${encodeURIComponent(call.id)}/grants?kind=${kind}`;
82
+ const body = { key: change.key, principal: customRolePrincipal(change.principal) };
81
83
  return method === 'grant' ? postJson({ ...call.request, path, body }) : deleteJson({ ...call.request, path, body });
82
84
  }
@@ -164,8 +164,10 @@ function validateV2Entry({ entry, index, ctx }) {
164
164
  const issue = (message, field) => ctx.addIssue({
165
165
  code: 'custom', message, path: ['primitives', index, ...(field ? [field] : [])],
166
166
  });
167
- if (entry.path.trim() !== entry.path || entry.path.includes('\\') || /^[A-Za-z]:/.test(entry.path) ||
168
- /[\x00-\x1f]/.test(entry.path) || entry.path.split('/').some((part) => ['', '.', '..'].includes(part))) {
167
+ // `.` alone is the root itself, where a repository index declares a root-level resource. As a segment of a
168
+ // longer path it stays refused, like `..`.
169
+ if (entry.path !== '.' && (entry.path.trim() !== entry.path || entry.path.includes('\\') || /^[A-Za-z]:/.test(entry.path) ||
170
+ /[\x00-\x1f]/.test(entry.path) || entry.path.split('/').some((part) => ['', '.', '..'].includes(part)))) {
169
171
  issue('path must be a relative directory within the app root', 'path');
170
172
  }
171
173
  if (new Set(entry.depends_on).size !== entry.depends_on.length)
@@ -41,6 +41,8 @@ declare const primitiveEntrySchema: z.ZodObject<{
41
41
  repo: z.ZodOptional<z.ZodString>;
42
42
  ref: z.ZodOptional<z.ZodString>;
43
43
  }, z.core.$strict>;
44
+ /** Every field a primitive entry accepts. A looser source (a repository index resource) carries more; those are not manifest fields. */
45
+ export declare const PRIMITIVE_ENTRY_FIELDS: readonly string[];
44
46
  /**
45
47
  * How YAML names a member's floor (the right to use it at all). `end_user` works
46
48
  * on every member; `invoker` is accepted on functions and processes, where it's
@@ -78,6 +78,8 @@ const primitiveEntrySchema = z
78
78
  });
79
79
  }
80
80
  });
81
+ /** Every field a primitive entry accepts. A looser source (a repository index resource) carries more; those are not manifest fields. */
82
+ export const PRIMITIVE_ENTRY_FIELDS = Object.keys(primitiveEntrySchema.shape);
81
83
  /** Custom-role key grammar, mirroring the Atlas registry. */
82
84
  const ROLE_KEY_RE = /^[a-z0-9-]{1,64}$/;
83
85
  const roleKeySchema = z.string().regex(ROLE_KEY_RE, 'role/capability keys are kebab-case (a-z, 0-9, -), at most 64 characters');
package/dist/app/paths.js CHANGED
@@ -21,6 +21,9 @@ export async function ensureAppOutputDirectory({ rootDir, entryPath }) {
21
21
  return directory;
22
22
  }
23
23
  function assertRelativePrimitivePath(entryPath) {
24
+ // The root itself; only a `.` inside a longer path is a traversal.
25
+ if (entryPath === '.')
26
+ return;
24
27
  const segments = entryPath.split('/');
25
28
  if (entryPath.length === 0 ||
26
29
  entryPath.trim() !== entryPath ||
@@ -0,0 +1,52 @@
1
+ /**
2
+ * What an artifact's `artifact.bundle.yml` says it reaches, read as data. A repository index declares
3
+ * resources without `depends_on`, so the bundle is the only place an app's dependencies are written.
4
+ *
5
+ * Read defensively and never through the strict manifest parser: a preview must still plan an app whose
6
+ * bundle this CLI's parser would refuse; the artifact's own build reports that.
7
+ */
8
+ /** The fields of a repository index resource that a bundle reference can name. */
9
+ export interface DependencyTarget {
10
+ id: string;
11
+ kind?: string;
12
+ namespace?: string;
13
+ slug?: string;
14
+ name?: string;
15
+ only?: unknown;
16
+ }
17
+ export type DependencyKind = 'orm' | 'function' | 'process' | 'workspace';
18
+ export interface BundleDependencies {
19
+ /** Ids of the index resources the bundle reaches, in the order the bundle names them. */
20
+ dependsOn: string[];
21
+ /** References no index resource declares. */
22
+ unresolved: Array<{
23
+ kind: DependencyKind;
24
+ name: string;
25
+ }>;
26
+ }
27
+ /**
28
+ * The index resources a bundle depends on. `resources` is the whole index, not only what was asked for: an
29
+ * app's namespace is often declared beside it, outside its directory.
30
+ */
31
+ export declare function inferBundleDependencies({ bundle, resources }: {
32
+ bundle: unknown;
33
+ resources: readonly DependencyTarget[];
34
+ }): BundleDependencies;
35
+ export type PrerequisiteKind = 'storage' | 'secret' | 'service-account' | 'namespace' | 'function' | 'process';
36
+ /** Something an artifact declares that a preview does not set up. */
37
+ export interface Prerequisite {
38
+ artifact: string;
39
+ kind: PrerequisiteKind;
40
+ name: string;
41
+ /** One line for the overview. */
42
+ detail: string;
43
+ }
44
+ /**
45
+ * What one artifact needs that the preview leaves to its operator: workspaces, server secrets, the service
46
+ * accounts external callers act as, and any dependency nothing in the repository declares.
47
+ */
48
+ export declare function artifactPrerequisites({ artifact, bundle, unresolved }: {
49
+ artifact: string;
50
+ bundle: unknown;
51
+ unresolved?: BundleDependencies['unresolved'];
52
+ }): Prerequisite[];
@@ -0,0 +1,121 @@
1
+ /**
2
+ * What an artifact's `artifact.bundle.yml` says it reaches, read as data. A repository index declares
3
+ * resources without `depends_on`, so the bundle is the only place an app's dependencies are written.
4
+ *
5
+ * Read defensively and never through the strict manifest parser: a preview must still plan an app whose
6
+ * bundle this CLI's parser would refuse; the artifact's own build reports that.
7
+ */
8
+ function at(value, ...keys) {
9
+ let current = value;
10
+ for (const key of keys)
11
+ current = typeof current === 'object' && current !== null ? Reflect.get(current, key) : undefined;
12
+ return current;
13
+ }
14
+ const strings = (value) => Array.isArray(value) ? value.filter((item) => typeof item === 'string' && item.length > 0) : [];
15
+ const keys = (value) => typeof value === 'object' && value !== null && !Array.isArray(value) ? Object.keys(value) : [];
16
+ const unique = (values) => [...new Set(values)];
17
+ /** The browser's and the server's capability blocks: a Next.js bundle has both, a static one only the first. */
18
+ const capabilityBlocks = (bundle) => [at(bundle, 'capabilities'), at(bundle, 'server', 'capabilities')];
19
+ /** `processes` is `{ start, read, act }` lists of process ids; a bare list is read the same way. */
20
+ function processRefs(value) {
21
+ if (Array.isArray(value))
22
+ return strings(value);
23
+ return keys(value).flatMap((access) => strings(at(value, access)));
24
+ }
25
+ function bundleReach(bundle) {
26
+ const blocks = capabilityBlocks(bundle);
27
+ return {
28
+ // `namespace/table` and `namespace/ops/Operation` both start with the namespace.
29
+ namespaces: unique(blocks.flatMap((block) => [...strings(at(block, 'data', 'read')), ...strings(at(block, 'data', 'write'))])
30
+ .map((ref) => ref.split('/')[0] ?? '').filter(Boolean)),
31
+ functions: unique(blocks.flatMap((block) => strings(at(block, 'functions', 'invoke')))),
32
+ processes: unique(blocks.flatMap((block) => processRefs(at(block, 'processes')))),
33
+ storage: unique(blocks.flatMap((block) => keys(at(block, 'storage')))),
34
+ };
35
+ }
36
+ const MATCHES = {
37
+ orm: (resource, name) => resource.namespace === name,
38
+ function: (resource, name) => resource.slug === name || resource.id === name,
39
+ // A process resource deploys the ids under `only`, or the one its own id names.
40
+ process: (resource, name) => strings(resource.only).includes(name) || resource.id === name,
41
+ workspace: (resource, name) => resource.name === name,
42
+ };
43
+ /**
44
+ * The index resources a bundle depends on. `resources` is the whole index, not only what was asked for: an
45
+ * app's namespace is often declared beside it, outside its directory.
46
+ */
47
+ export function inferBundleDependencies({ bundle, resources }) {
48
+ const reach = bundleReach(bundle);
49
+ const refs = [
50
+ ...reach.namespaces.map((name) => ({ kind: 'orm', name })),
51
+ ...reach.storage.map((name) => ({ kind: 'workspace', name })),
52
+ ...reach.functions.map((name) => ({ kind: 'function', name })),
53
+ ...reach.processes.map((name) => ({ kind: 'process', name })),
54
+ ];
55
+ const dependsOn = [];
56
+ const unresolved = [];
57
+ for (const ref of refs) {
58
+ const resource = resources.find((candidate) => candidate.kind === ref.kind && MATCHES[ref.kind](candidate, ref.name));
59
+ if (resource)
60
+ dependsOn.push(resource.id);
61
+ else
62
+ unresolved.push(ref);
63
+ }
64
+ return { dependsOn: unique(dependsOn), unresolved };
65
+ }
66
+ const UNRESOLVED = {
67
+ orm: { kind: 'namespace', detail: (name) => `namespace ${name}: no declared resource provides it, so it is not checked; this Atlas must already serve it` },
68
+ function: { kind: 'function', detail: (name) => `function ${name}: no declared resource provides it, so it is not deployed; this Atlas must already run it` },
69
+ process: { kind: 'process', detail: (name) => `process ${name}: no declared resource provides it, so it is not registered here` },
70
+ };
71
+ /**
72
+ * What one artifact needs that the preview leaves to its operator: workspaces, server secrets, the service
73
+ * accounts external callers act as, and any dependency nothing in the repository declares.
74
+ */
75
+ export function artifactPrerequisites({ artifact, bundle, unresolved = [] }) {
76
+ const undeclared = new Set(unresolved.filter((ref) => ref.kind === 'workspace').map((ref) => ref.name));
77
+ const storage = capabilityBlocks(bundle).flatMap((block) => {
78
+ const declared = at(block, 'storage');
79
+ return keys(declared).map((name) => ({ name, role: at(declared, name) }));
80
+ });
81
+ const seen = new Set();
82
+ const lines = [];
83
+ const add = (line) => {
84
+ if (seen.has(`${line.kind}\n${line.name}`))
85
+ return;
86
+ seen.add(`${line.kind}\n${line.name}`);
87
+ lines.push({ artifact, ...line });
88
+ };
89
+ for (const { name, role } of storage) {
90
+ add({
91
+ kind: 'storage',
92
+ name,
93
+ detail: `workspace ${name}${typeof role === 'string' ? ` (${role})` : ''}: not created here; it must exist on this Atlas` +
94
+ (undeclared.has(name) ? ', and no declared resource provides it' : ''),
95
+ });
96
+ }
97
+ const secrets = at(bundle, 'server', 'secrets');
98
+ for (const secret of Array.isArray(secrets) ? secrets : []) {
99
+ const name = typeof secret === 'string' ? secret : at(secret, 'name');
100
+ if (typeof name === 'string' && name)
101
+ add({ kind: 'secret', name, detail: `server secret ${name}: no value is supplied by this command` });
102
+ }
103
+ const external = at(bundle, 'server', 'ingress', 'external');
104
+ for (const ingress of Array.isArray(external) ? external : []) {
105
+ const account = at(ingress, 'service_account');
106
+ const id = at(ingress, 'id');
107
+ if (typeof account !== 'string' || !account)
108
+ continue;
109
+ add({
110
+ kind: 'service-account',
111
+ name: account,
112
+ detail: `service account ${account}${typeof id === 'string' ? ` (external ingress ${id})` : ''}: not created here; external callers act as it`,
113
+ });
114
+ }
115
+ for (const ref of unresolved) {
116
+ if (ref.kind === 'workspace')
117
+ continue;
118
+ add({ kind: UNRESOLVED[ref.kind].kind, name: ref.name, detail: UNRESOLVED[ref.kind].detail(ref.name) });
119
+ }
120
+ return lines;
121
+ }
@@ -1,7 +1,4 @@
1
1
  import type { ParsedArgs } from '../argv.js';
2
- /** Set where the local Atlas is reached through a tunnel, so the printed link opens for the viewer. */
3
- export declare const PREVIEW_ORIGIN_ENV = "SEQ_STUDIO_PREVIEW_ORIGIN";
4
- /** A directory of reviewed `<app id>.env` secret files, for machines provisioned to preview apps. */
5
- export declare const PREVIEW_SECRETS_DIR_ENV = "SEQ_STUDIO_PREVIEW_SECRETS_DIR";
6
- export declare const PREVIEW_USAGE = "usage: seq-studio preview [dir] -e local [--only <id>[,<id>...]] [--secrets <file>] [--apply-orm] [--watch] [--force] [--yes] [--json]\n\nStand up this app on a local Atlas and print where to open it. Reads sequence.app.yml and, in\ndependency order: checks each ORM namespace answers reads, deploys each function to the local\nruntime, and publishes each artifact to its preview channel. By default it previews the app's\nartifacts and what they depend on; --only names other primitives (a process, a function) to start.\n\nRuns only against a local Atlas on a personal or devbox database branch. It changes that database\ncopy and nothing else. Only the database is a copy: a function deployed here runs with the secret\nvalues you give it and reaches the real systems those credentials open. Declared egress is not\nenforced by the local runtime. Each function's egress and secret sources are shown before it deploys.\n\n --only <ids> preview these primitives and their dependencies instead of the artifacts\n --secrets <file> reviewed dotenv file of function secret values (default: $SEQ_STUDIO_PREVIEW_SECRETS_DIR/<app id>.env).\n A value may use ${preview.atlas_origin}, ${preview.database.host},\n ${preview.database.endpoint}, ${preview.database.name}, ${preview.database.branch}.\n ${env.NAME} takes the value from that variable of this command's environment.\n A secret with no value there or in this local Atlas stops the preview.\n --apply-orm apply each namespace's local definition to this database copy before checking it\n --watch keep rebuilding a static artifact on change (a Next.js app always stays attached)\n --force redeploy a function even when nothing it is built from changed. Needed after a\n credential held in an environment variable is rotated.\n --yes do not ask before deploying functions\n --json print the result as JSON\n\nSet SEQ_STUDIO_PREVIEW_ORIGIN to the URL you open the local Atlas at when that is not its own address.";
2
+ import { PREVIEW_APPS_ORIGIN_ENV, PREVIEW_ORIGIN_ENV, PREVIEW_SECRETS_DIR_ENV, PREVIEW_USAGE } from './usage.js';
3
+ export { PREVIEW_APPS_ORIGIN_ENV, PREVIEW_ORIGIN_ENV, PREVIEW_SECRETS_DIR_ENV, PREVIEW_USAGE };
7
4
  export declare function runPreviewCommand(args: ParsedArgs): Promise<number>;
@@ -2,48 +2,24 @@ import { existsSync } from 'node:fs';
2
2
  import { readFile } from 'node:fs/promises';
3
3
  import { join, resolve } from 'node:path';
4
4
  import { getJsonOr404 } from '../atlas-client.js';
5
- import { loadAppManifest } from '../app/manifest.js';
6
5
  import { ExitCode, UsageError } from '../exit-codes.js';
7
6
  import { buildContext, clientOptions, flagBool, parseDotenv, requestedEnvironment } from '../functions/commands.js';
8
7
  import { resolveConfiguredEnv } from '../config.js';
9
8
  import { REQUIRE_EXPLICIT_ENV_MESSAGE } from '../env-flags.js';
10
9
  import { isLoopbackUrl } from '../host-token.js';
11
10
  import { confirmYes, LOG } from '../prompt.js';
11
+ import { artifactPrerequisites } from './bundle-dependencies.js';
12
12
  import { planPreview } from './plan.js';
13
+ import { loadPreviewManifest, ormApplyScope } from './repository-manifest.js';
14
+ import { forkResult, outstandingPrerequisites, planFork, runNextSession, setUpFork } from './fork-setup.js';
15
+ import { forkReport, functionReport, prerequisiteReport, processRegistrationHint, sourceReport } from './report.js';
13
16
  import { previewSucceeded, runPreviewPlan } from './run.js';
17
+ import { attached } from './session-output.js';
18
+ import { mountSourceIncludes } from './source-includes.js';
14
19
  import { applyProcess, checkNamespace, deployFunction, inspectArtifact, DEFAULT_PREVIEW_KEY, ensureArtifactDependencies, inspectFunction, publishStaticArtifact, } from './runners.js';
15
- import { describeSecretSource } from './secrets.js';
16
20
  import { decidePreviewTarget } from './target.js';
17
- /** Set where the local Atlas is reached through a tunnel, so the printed link opens for the viewer. */
18
- export const PREVIEW_ORIGIN_ENV = 'SEQ_STUDIO_PREVIEW_ORIGIN';
19
- /** A directory of reviewed `<app id>.env` secret files, for machines provisioned to preview apps. */
20
- export const PREVIEW_SECRETS_DIR_ENV = 'SEQ_STUDIO_PREVIEW_SECRETS_DIR';
21
- export const PREVIEW_USAGE = `usage: seq-studio preview [dir] -e local [--only <id>[,<id>...]] [--secrets <file>] [--apply-orm] [--watch] [--force] [--yes] [--json]
22
-
23
- Stand up this app on a local Atlas and print where to open it. Reads sequence.app.yml and, in
24
- dependency order: checks each ORM namespace answers reads, deploys each function to the local
25
- runtime, and publishes each artifact to its preview channel. By default it previews the app's
26
- artifacts and what they depend on; --only names other primitives (a process, a function) to start.
27
-
28
- Runs only against a local Atlas on a personal or devbox database branch. It changes that database
29
- copy and nothing else. Only the database is a copy: a function deployed here runs with the secret
30
- values you give it and reaches the real systems those credentials open. Declared egress is not
31
- enforced by the local runtime. Each function's egress and secret sources are shown before it deploys.
32
-
33
- --only <ids> preview these primitives and their dependencies instead of the artifacts
34
- --secrets <file> reviewed dotenv file of function secret values (default: $${PREVIEW_SECRETS_DIR_ENV}/<app id>.env).
35
- A value may use \${preview.atlas_origin}, \${preview.database.host},
36
- \${preview.database.endpoint}, \${preview.database.name}, \${preview.database.branch}.
37
- \${env.NAME} takes the value from that variable of this command's environment.
38
- A secret with no value there or in this local Atlas stops the preview.
39
- --apply-orm apply each namespace's local definition to this database copy before checking it
40
- --watch keep rebuilding a static artifact on change (a Next.js app always stays attached)
41
- --force redeploy a function even when nothing it is built from changed. Needed after a
42
- credential held in an environment variable is rotated.
43
- --yes do not ask before deploying functions
44
- --json print the result as JSON
45
-
46
- Set ${PREVIEW_ORIGIN_ENV} to the URL you open the local Atlas at when that is not its own address.`;
21
+ import { PREVIEW_APPS_ORIGIN_ENV, PREVIEW_ORIGIN_ENV, PREVIEW_SECRETS_DIR_ENV, PREVIEW_USAGE } from './usage.js';
22
+ export { PREVIEW_APPS_ORIGIN_ENV, PREVIEW_ORIGIN_ENV, PREVIEW_SECRETS_DIR_ENV, PREVIEW_USAGE };
47
23
  function csv(value) {
48
24
  if (typeof value !== 'string')
49
25
  return undefined;
@@ -81,23 +57,6 @@ function publicOrigin(atlasOrigin) {
81
57
  throw new UsageError(`${PREVIEW_ORIGIN_ENV} must be an http(s) URL`);
82
58
  return url.origin;
83
59
  }
84
- function functionReport(inspection) {
85
- const lines = [`${LOG} function ${inspection.slug} (${inspection.entry.id})`];
86
- lines.push(inspection.egress.length
87
- ? `${LOG} declares egress to: ${inspection.egress.join(', ')}`
88
- : `${LOG} declares no egress`);
89
- lines.push(`${LOG} egress is NOT enforced here: the local runtime can reach any host its credentials open`);
90
- if (inspection.secrets.sources.length === 0 && inspection.unavailableSets.length === 0) {
91
- lines.push(`${LOG} secrets: none declared`);
92
- }
93
- for (const source of inspection.secrets.sources) {
94
- lines.push(`${LOG} secret ${source.name}: ${describeSecretSource(source)}`);
95
- }
96
- for (const set of inspection.unavailableSets) {
97
- lines.push(`${LOG} key/value set ${set}: NO VALUE in this local Atlas`);
98
- }
99
- return lines;
100
- }
101
60
  function missingSecretsMessage({ inspections, secretsFile, appId }) {
102
61
  const lines = [];
103
62
  for (const inspection of inspections) {
@@ -127,7 +86,7 @@ function printSummary({ results, plan, target }) {
127
86
  }
128
87
  }
129
88
  /** Decide the target, refusing a hosted environment before signing in to it or sending it anything. */
130
- async function resolveTarget({ args, envName, rootDir }) {
89
+ async function resolveTarget({ args, envName, rootDir, source }) {
131
90
  const requested = await resolveConfiguredEnv({ requested: envName });
132
91
  const hosted = decidePreviewTarget({ envName: requested.name, url: requested.url, report: null });
133
92
  if (!isLoopbackUrl(requested.url) && !hosted.ok) {
@@ -144,12 +103,19 @@ async function resolveTarget({ args, envName, rootDir }) {
144
103
  }
145
104
  return {
146
105
  rootDir,
106
+ source,
147
107
  env: command.env.name,
148
108
  client,
149
109
  target: decision.target,
150
110
  publicOrigin: publicOrigin(decision.target.origin),
151
111
  };
152
112
  }
113
+ /** Check a namespace, applying it first when `--apply-orm` reaches it; a namespace it does not reach says so. */
114
+ async function namespaceStep({ ctx, entry, applyOrm, preview, only, started }) {
115
+ const scope = ormApplyScope({ applyOrm, entry, preview, only, started });
116
+ const outcome = await checkNamespace({ ctx, entry, apply: scope.apply });
117
+ return scope.note ? { ...outcome, detail: `${outcome.detail}; ${scope.note}` } : outcome;
118
+ }
153
119
  export async function runPreviewCommand(args) {
154
120
  if (args.flags.help === true || args.flags.h === true) {
155
121
  console.log(PREVIEW_USAGE);
@@ -161,10 +127,14 @@ export async function runPreviewCommand(args) {
161
127
  return ExitCode.Usage;
162
128
  }
163
129
  const json = flagBool(args.flags, 'json');
164
- const rootDir = resolve(args.positional[0] ?? (typeof args.flags.dir === 'string' ? args.flags.dir : '.'));
165
- const manifest = await loadAppManifest(rootDir);
166
- const plan = planPreview({ manifest, only: csv(args.flags.only) });
167
- const resolved = await resolveTarget({ args, envName, rootDir });
130
+ const only = csv(args.flags.only);
131
+ const preview = await loadPreviewManifest({
132
+ dir: args.positional[0] ?? (typeof args.flags.dir === 'string' ? args.flags.dir : '.'),
133
+ only,
134
+ });
135
+ const { manifest } = preview;
136
+ const plan = planPreview({ manifest, only });
137
+ const resolved = await resolveTarget({ args, envName, rootDir: preview.rootDir, source: preview.source });
168
138
  if (typeof resolved === 'number')
169
139
  return resolved;
170
140
  const ctx = resolved;
@@ -182,10 +152,23 @@ export async function runPreviewCommand(args) {
182
152
  if (nextApps.length > 1) {
183
153
  throw new UsageError(`A Next.js preview stays attached to this terminal, so one command starts one: pass --only with one of ${nextApps.map((app) => app.entry.id).join(', ')}.`);
184
154
  }
155
+ const forkPlan = await planFork({
156
+ ctx,
157
+ flags: args.flags,
158
+ artifacts: [...artifacts.values()],
159
+ workspaces: plan.steps.flatMap((step) => (step.entry.kind === 'workspace' && step.entry.name ? [step.entry.name] : [])),
160
+ next: nextApps[0],
161
+ });
162
+ const prerequisites = [...artifacts.values()].flatMap((artifact) => artifactPrerequisites({ artifact: artifact.entry.id, bundle: artifact.bundle, unresolved: preview.unresolved[artifact.entry.id] }));
185
163
  const overview = [
186
164
  `${LOG} previewing ${manifest.app.id} on the local Atlas at ${ctx.target.origin} (database branch ${ctx.target.database.branch})`,
165
+ ...sourceReport(preview),
187
166
  `${LOG} steps: ${plan.steps.map((step) => step.entry.id).join(' -> ')}`,
188
167
  ...[...functions.values()].flatMap(functionReport),
168
+ // What this run is about to set up itself is announced by forkReport, not listed as left undone.
169
+ ...prerequisiteReport(prerequisites.filter((line) => !forkPlan.handled.has(line.kind))),
170
+ ...processRegistrationHint({ preview, plan, prerequisites }),
171
+ ...forkReport(forkPlan),
189
172
  ];
190
173
  const missing = missingSecretsMessage({ inspections: [...functions.values()], secretsFile: secrets.file, appId: manifest.app.id });
191
174
  if (missing.length) {
@@ -202,13 +185,14 @@ export async function runPreviewCommand(args) {
202
185
  say(line);
203
186
  if (startsCode && !(await confirmYes({ preview: [], confirmed: flagBool(args.flags, 'yes') })))
204
187
  return ExitCode.Failed;
188
+ const forkSetup = await setUpFork({ ctx, plan: forkPlan, say });
205
189
  const applyOrm = flagBool(args.flags, 'apply-orm');
206
190
  const results = await runPreviewPlan({
207
191
  plan,
208
192
  run: async (step) => {
209
193
  switch (step.action) {
210
194
  case 'check-namespace':
211
- return checkNamespace({ ctx, entry: step.entry, apply: applyOrm });
195
+ return namespaceStep({ ctx, entry: step.entry, applyOrm, preview, only, started: plan.selected });
212
196
  case 'deploy-function':
213
197
  return deployFunction({ ctx, inspection: functions.get(step.entry.id), force: flagBool(args.flags, 'force') });
214
198
  case 'apply-process':
@@ -227,10 +211,13 @@ export async function runPreviewCommand(args) {
227
211
  console.log(JSON.stringify({
228
212
  ok,
229
213
  app: manifest.app.id,
214
+ source: preview.source,
230
215
  atlas: ctx.target.origin,
231
216
  database: { branch: ctx.target.database.branch },
232
217
  steps: results,
233
218
  omitted: plan.omitted.map((entry) => entry.id),
219
+ prerequisites: outstandingPrerequisites({ prerequisites, plan: forkPlan, setup: forkSetup }),
220
+ ...forkResult({ plan: forkPlan, setup: forkSetup }),
234
221
  urls: results.flatMap((result) => (result.url ? [result.url] : [])),
235
222
  }));
236
223
  }
@@ -239,10 +226,10 @@ export async function runPreviewCommand(args) {
239
226
  }
240
227
  if (!ok)
241
228
  return ExitCode.Failed;
242
- return attachSession({ ctx, next: nextApps[0], watched: flagBool(args.flags, 'watch') ? [...artifacts.values()][0] : undefined });
229
+ return attachSession({ ctx, json, next: nextApps[0], secretArgs: forkPlan.secretArgs, watched: flagBool(args.flags, 'watch') ? [...artifacts.values()][0] : undefined });
243
230
  }
244
231
  /** A Next.js app, or a watched static one, keeps this command attached until it is stopped. */
245
- async function attachSession({ ctx, next, watched }) {
232
+ async function attachSession({ ctx, json, next, watched, secretArgs }) {
246
233
  if (!next && !watched)
247
234
  return ExitCode.Ok;
248
235
  const { runArtifactCommand } = await import('../artifact/delegate.js');
@@ -252,13 +239,21 @@ async function attachSession({ ctx, next, watched }) {
252
239
  return ExitCode.Failed;
253
240
  }
254
241
  if (next) {
242
+ const includes = await mountSourceIncludes({ artifactDir: next.dir, bundle: next.bundle });
243
+ if (includes.mounted.length)
244
+ console.error(`${LOG} copied source includes ${includes.mounted.join(', ')} to .artifact-includes, as the hosted build mounts them`);
245
+ if (includes.missing.length)
246
+ console.error(`${LOG} source includes ${includes.missing.join(', ')} are not in this checkout; imports from them will not resolve`);
255
247
  console.error(`${LOG} starting the Next.js session for ${next.projectId}; it runs until you stop it (Ctrl+C).`);
256
- console.error(`${LOG} its link is served by the local app gateway, which a remote viewer must also be able to reach.`);
257
- if (ctx.publicOrigin !== ctx.target.origin) {
258
- console.error(`${LOG} the link below is printed on ${ctx.target.origin}; open the same path on ${ctx.publicOrigin}`);
248
+ // The session prints its own link for a remote viewer when the app gateway has a tunnel too.
249
+ if (ctx.publicOrigin !== ctx.target.origin && !process.env[PREVIEW_APPS_ORIGIN_ENV]?.trim()) {
250
+ console.error(`${LOG} this box has no app tunnel yet (its sandbox was created before Next.js previews opened remotely): suspend and resume it, or view the app in-box.`);
259
251
  }
260
- return runArtifactCommand('dev', [next.dir, '--env', ctx.env]);
252
+ return attached({
253
+ json,
254
+ run: () => runNextSession({ run: () => runArtifactCommand('dev', [next.dir, '--env', ctx.env, ...secretArgs]), dir: next.dir, upstream: secretArgs.includes('upstream') }),
255
+ });
261
256
  }
262
257
  console.error(`${LOG} watching ${watched.projectId} for changes (Ctrl+C to stop)`);
263
- return runArtifactCommand('dev', [watched.dir, '--env', ctx.env, '--key', DEFAULT_PREVIEW_KEY]);
258
+ return attached({ json, run: () => runArtifactCommand('dev', [watched.dir, '--env', ctx.env, '--key', DEFAULT_PREVIEW_KEY]) });
264
259
  }
@@ -0,0 +1,66 @@
1
+ import { type BindingPruneOutcome, type IdentityAdmissionOutcome, type PreviewFork, type SecretSourceDecision, type WorkspaceAdoptionOutcome } from './fork.js';
2
+ import type { Prerequisite } from './bundle-dependencies.js';
3
+ import type { ArtifactInspection, PreviewContext } from './runners.js';
4
+ export interface ForkPlan {
5
+ /** Set when the local Atlas reports a devbox fork. */
6
+ fork: PreviewFork | undefined;
7
+ /** The workspaces to adopt, on a fork only: every name an artifact declares and every workspace primitive planned. */
8
+ workspaceNames: string[];
9
+ next: ArtifactInspection | undefined;
10
+ secretNames: string[];
11
+ /** Where the Next.js session's secrets come from; undefined when no Next.js app is previewed. */
12
+ secretSource: SecretSourceDecision | undefined;
13
+ /** Flags for `artifact dev` that select that source: names and sources only. */
14
+ secretArgs: readonly string[];
15
+ /** Prerequisite kinds this run intends to set up itself, for the overview printed before it tries. */
16
+ handled: ReadonlySet<string>;
17
+ }
18
+ export declare function planFork({ ctx, flags, artifacts, workspaces, next }: {
19
+ ctx: PreviewContext;
20
+ flags: Record<string, unknown>;
21
+ artifacts: readonly ArtifactInspection[];
22
+ /** Names of the workspace primitives this preview plans. A bundle may reach one by id, which names nothing. */
23
+ workspaces?: readonly string[];
24
+ next: ArtifactInspection | undefined;
25
+ }): Promise<ForkPlan>;
26
+ export interface ForkSetup {
27
+ workspaces: WorkspaceAdoptionOutcome | null;
28
+ identities: IdentityAdmissionOutcome | null;
29
+ bindings: BindingPruneOutcome | null;
30
+ }
31
+ /**
32
+ * Before anything starts on a devbox fork: adopt the declared workspaces from the database copy,
33
+ * admit the identities the copied Next.js project records, and drop the development bindings it
34
+ * records for resources the application no longer declares. None failing stops the preview; each
35
+ * says what it left undone, and the session start then reports the same gap by name.
36
+ */
37
+ export declare function setUpFork({ ctx, plan, say }: {
38
+ ctx: PreviewContext;
39
+ plan: ForkPlan;
40
+ say: (line: string) => void;
41
+ }): Promise<ForkSetup | undefined>;
42
+ /**
43
+ * What is still left to the operator once the fork steps have run: the result document lists a
44
+ * prerequisite unless this run really satisfied it. A workspace that was not adopted, secrets no
45
+ * source supplies, and identities that were not admitted all stay listed.
46
+ */
47
+ export declare function outstandingPrerequisites({ prerequisites, plan, setup }: {
48
+ prerequisites: readonly Prerequisite[];
49
+ plan: ForkPlan;
50
+ setup: ForkSetup | undefined;
51
+ }): Prerequisite[];
52
+ /** The `fork` member of the `--json` result, on a devbox fork only. Names and statuses; a secret value never reaches this command. */
53
+ export declare function forkResult({ plan, setup }: {
54
+ plan: ForkPlan;
55
+ setup: ForkSetup | undefined;
56
+ }): Record<string, unknown>;
57
+ /**
58
+ * Reading secrets from the fork source is implemented by this CLI's own Artifact Studio. A
59
+ * repository that runs its installed copy instead may predate it, so that one session uses the
60
+ * bundled copy. An explicit `--sdk` or SEQ_STUDIO_SDK is left alone, as everywhere else.
61
+ */
62
+ export declare function runNextSession({ run, dir, upstream }: {
63
+ run: () => Promise<number>;
64
+ dir: string;
65
+ upstream: boolean;
66
+ }): Promise<number>;