@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
@@ -1,5 +1,5 @@
1
1
  import { existsSync } from 'node:fs';
2
- import { chmod, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
2
+ import { chmod, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises';
3
3
  import { tmpdir } from 'node:os';
4
4
  import { join } from 'node:path';
5
5
  import { parse as parseYaml } from 'yaml';
@@ -7,18 +7,50 @@ import { getJson, getJsonOr404, postJsonResponse } from '../atlas-client.js';
7
7
  import { resolveContainedPrimitivePath } from '../app/paths.js';
8
8
  import { schemaViewSchema } from '../orm/discover-schema.js';
9
9
  import { fingerprintMessage, fingerprintOf, functionFingerprint } from './fingerprint.js';
10
- import { decideInstall, installDependencies } from './install.js';
10
+ import { decideInstall, installDependencies, repositoryInstallRoot } from './install.js';
11
11
  import { interpretNamespaceProbe } from './namespace-probe.js';
12
+ import { chooseOrmSdk, installOrmMessage } from './orm-sdk.js';
12
13
  import { planFunctionSecrets, secretsEnvFile } from './secrets.js';
13
14
  export const primitiveDir = ({ ctx, entry }) => resolveContainedPrimitivePath({ rootDir: ctx.rootDir, entryPath: entry.path });
14
15
  const quoted = (identifier) => `"${identifier.replaceAll('"', '""')}"`;
16
+ const ORM_PACKAGE = '@sequenceholdings/orm';
17
+ /**
18
+ * Apply a namespace's local definition with an ORM its pinned range accepts. An explicit `--sdk` or
19
+ * SEQ_STUDIO_SDK is left alone. Returns a failure outcome, or undefined when the apply succeeded.
20
+ */
21
+ async function applyNamespace({ ctx, entry, namespace }) {
22
+ const dir = await primitiveDir({ ctx, entry });
23
+ const { bundledSdk, projectSdk, SDK_ENV } = await import('../sdk-source.js');
24
+ const { pinnedOrmRange } = await import('../orm/version-guard.js');
25
+ const choice = process.env[SDK_ENV]?.trim()
26
+ ? { use: 'default' }
27
+ : chooseOrmSdk({
28
+ range: await pinnedOrmRange(dir),
29
+ bundled: bundledSdk({ name: ORM_PACKAGE })?.version,
30
+ project: projectSdk({ name: ORM_PACKAGE, cwd: dir })?.version,
31
+ });
32
+ if (choice.use === 'install')
33
+ return { status: 'failed', detail: installOrmMessage({ namespace, dir, choice }) };
34
+ const { runOrmCommand } = await import('../orm/delegate.js');
35
+ if (choice.use === 'project')
36
+ process.env[SDK_ENV] = 'project';
37
+ let code;
38
+ try {
39
+ code = await runOrmCommand('apply', [dir, '--env', ctx.env]);
40
+ }
41
+ finally {
42
+ // Only this namespace asked for its own copy; the next step decides again.
43
+ if (choice.use === 'project')
44
+ delete process.env[SDK_ENV];
45
+ }
46
+ return code === 0 ? undefined : { status: 'failed', detail: `seq-studio orm apply for ${namespace} exited ${code}` };
47
+ }
15
48
  export async function checkNamespace({ ctx, entry, apply }) {
16
49
  const namespace = entry.namespace;
17
50
  if (apply) {
18
- const { runOrmCommand } = await import('../orm/delegate.js');
19
- const code = await runOrmCommand('apply', [await primitiveDir({ ctx, entry }), '--env', ctx.env]);
20
- if (code !== 0)
21
- return { status: 'failed', detail: `seq-studio orm apply for ${namespace} exited ${code}` };
51
+ const failed = await applyNamespace({ ctx, entry, namespace });
52
+ if (failed)
53
+ return failed;
22
54
  }
23
55
  const schemaBody = await getJsonOr404({
24
56
  ...ctx.client,
@@ -27,8 +59,8 @@ export async function checkNamespace({ ctx, entry, apply }) {
27
59
  if (schemaBody === null)
28
60
  return interpretNamespaceProbe({ namespace, status: 404, body: null });
29
61
  const schema = schemaViewSchema.safeParse(schemaBody);
30
- const relation = schema.success ? (schema.data.tables[0]?.table ?? schema.data.views[0]?.view) : undefined;
31
- if (typeof relation !== 'string') {
62
+ const relations = schema.success ? probeRelations(schema.data) : [];
63
+ if (relations.length === 0) {
32
64
  return { status: 'ready', detail: `namespace ${namespace} is registered and has no tables to read` };
33
65
  }
34
66
  const { createOperationExecutorWithTransport } = await import('@sequenceholdings/orm/client');
@@ -50,19 +82,29 @@ export async function checkNamespace({ ctx, entry, apply }) {
50
82
  });
51
83
  // A local Atlas repairs a missing owner-role membership when it next resolves the owner, which
52
84
  // can be the request after the one that failed. One retry tells a repaired namespace from a broken one.
53
- for (let attempt = 0; attempt < 2; attempt += 1) {
54
- try {
55
- await executor.sql({ sql: `SELECT * FROM ${quoted(namespace)}.${quoted(relation)} LIMIT 1` });
56
- }
57
- catch (error) {
58
- if (seen.status === 0)
59
- throw error;
85
+ for (const relation of relations) {
86
+ for (let attempt = 0; attempt < 2; attempt += 1) {
87
+ try {
88
+ await executor.sql({ sql: `SELECT * FROM ${quoted(namespace)}.${quoted(relation)} LIMIT 1` });
89
+ }
90
+ catch (error) {
91
+ if (seen.status === 0)
92
+ throw error;
93
+ }
94
+ if (seen.status !== 500)
95
+ break;
60
96
  }
61
- if (seen.status !== 500)
97
+ // The data plane refuses raw SQL on some relations (a synced table) on every Atlas, the
98
+ // fork's parent included. That says nothing about the namespace, so read the next one.
99
+ if (seen.status !== 400)
62
100
  break;
63
101
  }
64
102
  return interpretNamespaceProbe({ namespace, ...seen });
65
103
  }
104
+ /** Relations to try reading, in order: every table, then every view. */
105
+ export function probeRelations({ tables, views }) {
106
+ return [...tables.map(({ table }) => table), ...views.map(({ view }) => view)];
107
+ }
66
108
  /** Read what a function will be able to reach and where its secrets come from, before anything deploys. */
67
109
  export async function inspectFunction({ ctx, entry, provided, providedFile }) {
68
110
  const { readManifestOptional } = await import('../functions/commands.js');
@@ -168,18 +210,30 @@ export async function inspectArtifact({ ctx, entry }) {
168
210
  const raw = parseYaml(await readFile(path, 'utf8'));
169
211
  const artifact = typeof raw === 'object' && raw !== null ? Reflect.get(raw, 'artifact') : undefined;
170
212
  const type = typeof artifact === 'object' && artifact !== null ? Reflect.get(artifact, 'type') : undefined;
171
- return { entry, dir, projectId: entry.project_id, nextjs: type === 'nextjs' };
213
+ return { entry, dir, projectId: entry.project_id, nextjs: type === 'nextjs', bundle: raw };
172
214
  }
173
- /** Install a fresh clone's dependencies. Returns a failure outcome, or undefined when the artifact can build. */
174
- export async function ensureArtifactDependencies({ ctx, inspection }) {
175
- const decision = decideInstall({ artifactDir: inspection.dir, appRoot: ctx.rootDir });
215
+ /**
216
+ * Install a fresh clone's dependencies for the code in `dir`. Returns a failure outcome, or undefined
217
+ * when it can build. `label` names what is being installed for, in the progress line.
218
+ */
219
+ async function ensureDependencies({ ctx, dir, label }) {
220
+ // An app's manifest sits at its workspace root. A repository index says nothing about workspaces, and
221
+ // the lockfile may be above the requested directory (or the code outside it, named with --only).
222
+ const appRoot = ctx.source === 'app-manifest'
223
+ ? ctx.rootDir
224
+ : repositoryInstallRoot({ artifactDir: dir, gitRoot: await realpath(ctx.rootDir) });
225
+ const decision = decideInstall({ artifactDir: dir, appRoot });
176
226
  if (!decision.install)
177
227
  return undefined;
178
- console.error(`[seq-studio] installing dependencies for ${inspection.projectId}: pnpm ${decision.args.join(' ')} (in ${decision.root})`);
228
+ console.error(`[seq-studio] installing dependencies for ${label}: pnpm ${decision.args.join(' ')} (in ${decision.root})`);
179
229
  const code = await installDependencies(decision);
180
230
  return code === 0
181
231
  ? undefined
182
- : { status: 'failed', detail: `pnpm ${decision.args.join(' ')} in ${decision.root} exited ${code}; the artifact cannot build without its dependencies` };
232
+ : { status: 'failed', detail: `pnpm ${decision.args.join(' ')} in ${decision.root} exited ${code}; ${label} cannot build without its dependencies` };
233
+ }
234
+ /** Install a fresh clone's dependencies. Returns a failure outcome, or undefined when the artifact can build. */
235
+ export async function ensureArtifactDependencies({ ctx, inspection }) {
236
+ return ensureDependencies({ ctx, dir: inspection.dir, label: inspection.projectId });
183
237
  }
184
238
  /** The preview key a bare preview URL shows, so the link works with no query string to lose. */
185
239
  export const DEFAULT_PREVIEW_KEY = 'default';
@@ -211,11 +265,17 @@ export async function publishStaticArtifact({ ctx, inspection }) {
211
265
  };
212
266
  }
213
267
  export async function applyProcess({ ctx, entry }) {
268
+ const dir = await primitiveDir({ ctx, entry });
269
+ // Process code imports its SDK like any package; a fresh clone has none installed, and building then
270
+ // fails on the first import.
271
+ const failed = await ensureDependencies({ ctx, dir, label: `process ${entry.id}` });
272
+ if (failed)
273
+ return failed;
214
274
  const { applyCommand } = await import('../process/commands.js');
215
275
  const code = await applyCommand({
216
276
  positional: [],
217
277
  flags: {
218
- dir: await primitiveDir({ ctx, entry }),
278
+ dir,
219
279
  env: ctx.env,
220
280
  ...(entry.only?.length ? { only: entry.only.join(',') } : {}),
221
281
  },
@@ -0,0 +1,5 @@
1
+ /** Run a session that writes to stdout for as long as it lives, without it reaching a `--json` reader's document. */
2
+ export declare function attached({ json, run }: {
3
+ json: boolean;
4
+ run: () => Promise<number>;
5
+ }): Promise<number>;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Under `--json`, stdout carries the result document and nothing else. An attached dev session runs in this
3
+ * process and writes there, both its own lines and the dev server's piped output, so while it is attached
4
+ * everything written to stdout goes to stderr instead. Returns the function that puts stdout back.
5
+ */
6
+ function sendStdoutToStderr() {
7
+ const log = console.log;
8
+ const write = process.stdout.write;
9
+ console.log = (...args) => console.error(...args);
10
+ // Both are Writable#write on the same stream class; only the destination differs.
11
+ process.stdout.write = process.stderr.write.bind(process.stderr);
12
+ return () => {
13
+ console.log = log;
14
+ process.stdout.write = write;
15
+ };
16
+ }
17
+ /** Run a session that writes to stdout for as long as it lives, without it reaching a `--json` reader's document. */
18
+ export async function attached({ json, run }) {
19
+ if (!json)
20
+ return run();
21
+ const restore = sendStdoutToStderr();
22
+ try {
23
+ return await run();
24
+ }
25
+ finally {
26
+ restore();
27
+ }
28
+ }
@@ -0,0 +1,12 @@
1
+ /** The include paths a bundle declares, repository-relative. A path that could leave the repository is not one. */
2
+ export declare function declaredSourceIncludes(bundle: unknown): string[];
3
+ export interface SourceIncludeMount {
4
+ mounted: string[];
5
+ /** Declared, but neither in this checkout nor already at the mount: the app will not compile without it. */
6
+ missing: string[];
7
+ }
8
+ /** Copy each declared include from the checkout to the app's mount, replacing what was there. */
9
+ export declare function mountSourceIncludes({ artifactDir, bundle }: {
10
+ artifactDir: string;
11
+ bundle: unknown;
12
+ }): Promise<SourceIncludeMount>;
@@ -0,0 +1,74 @@
1
+ /**
2
+ * A Next.js bundle may declare `build.source_includes`: repository directories the hosted build
3
+ * places under `.artifact-includes/` in the app root and the app imports through a path alias. A
4
+ * development session compiles the checkout as it is, so the same directories are copied to the
5
+ * same mount before it starts. A copy, as on the hosted build: imports in an include must resolve
6
+ * the app's own node_modules.
7
+ */
8
+ import { existsSync } from 'node:fs';
9
+ import { cp, lstat, mkdir, rm, unlink } from 'node:fs/promises';
10
+ import { basename, dirname, isAbsolute, join } from 'node:path';
11
+ const MOUNT = '.artifact-includes';
12
+ const SKIPPED = new Set(['node_modules', '.next', '.git', MOUNT]);
13
+ function at(value, ...keys) {
14
+ let current = value;
15
+ for (const key of keys)
16
+ current = typeof current === 'object' && current !== null ? Reflect.get(current, key) : undefined;
17
+ return current;
18
+ }
19
+ const withinRepository = (path) => path.length > 0 && !isAbsolute(path) && path.split('/').every((part) => part !== '' && part !== '.' && part !== '..' && !SKIPPED.has(part));
20
+ /** The include paths a bundle declares, repository-relative. A path that could leave the repository is not one. */
21
+ export function declaredSourceIncludes(bundle) {
22
+ const includes = at(bundle, 'build', 'source_includes');
23
+ const paths = (Array.isArray(includes) ? includes : []).map((include) => at(include, 'path'));
24
+ return [...new Set(paths.filter((path) => typeof path === 'string' && withinRepository(path)))];
25
+ }
26
+ function gitRootOf(directory) {
27
+ for (let current = directory;; current = dirname(current)) {
28
+ if (existsSync(join(current, '.git')))
29
+ return current;
30
+ if (dirname(current) === current)
31
+ return undefined;
32
+ }
33
+ }
34
+ /**
35
+ * Remove the first link on the way from the mount down to an include. Deleting the include through
36
+ * a link would delete what the link points at: `.artifact-includes/shared` linked to the
37
+ * repository's `shared` makes the target the source itself.
38
+ */
39
+ async function unlinkMountLink({ mount, path }) {
40
+ let current = mount;
41
+ for (const part of ['', ...path.split('/')]) {
42
+ current = join(current, part);
43
+ const stats = await lstat(current).catch(() => undefined);
44
+ if (!stats)
45
+ return;
46
+ if (stats.isSymbolicLink())
47
+ return unlink(current);
48
+ }
49
+ }
50
+ /** Copy each declared include from the checkout to the app's mount, replacing what was there. */
51
+ export async function mountSourceIncludes({ artifactDir, bundle }) {
52
+ const includes = declaredSourceIncludes(bundle);
53
+ const result = { mounted: [], missing: [] };
54
+ if (includes.length === 0)
55
+ return result;
56
+ const appRoot = at(bundle, 'artifact', 'app_root');
57
+ const mount = join(artifactDir, typeof appRoot === 'string' && withinRepository(appRoot) ? appRoot : '.', MOUNT);
58
+ const repository = gitRootOf(artifactDir);
59
+ for (const path of includes) {
60
+ const source = repository ? join(repository, path) : undefined;
61
+ const target = join(mount, path);
62
+ if (!source || !existsSync(source)) {
63
+ if (!existsSync(target))
64
+ result.missing.push(path);
65
+ continue;
66
+ }
67
+ await unlinkMountLink({ mount, path });
68
+ await rm(target, { recursive: true, force: true });
69
+ await mkdir(dirname(target), { recursive: true });
70
+ await cp(source, target, { recursive: true, filter: (entry) => !SKIPPED.has(basename(entry)) });
71
+ result.mounted.push(path);
72
+ }
73
+ return result;
74
+ }
@@ -6,6 +6,14 @@ export interface PreviewTarget {
6
6
  endpoint?: string;
7
7
  name?: string;
8
8
  };
9
+ /**
10
+ * A devbox's copy of another deployment's database: that deployment's environment name when Atlas
11
+ * resolves it, and whether it releases development secret values (false unless Atlas says so).
12
+ */
13
+ fork?: {
14
+ upstreamEnvironment: string | null;
15
+ upstreamSecrets: boolean;
16
+ };
9
17
  }
10
18
  export type PreviewTargetDecision = {
11
19
  ok: true;
@@ -11,6 +11,8 @@ const localRuntimeReportSchema = z.looseObject({
11
11
  name: z.string().optional(),
12
12
  }),
13
13
  functions: z.looseObject({ localRuntime: z.boolean() }),
14
+ /** Present when the database is a devbox's copy of another deployment's. */
15
+ fork: z.looseObject({ devbox: z.literal(true), upstreamEnvironment: z.string().nullable(), upstreamSecrets: z.boolean().optional() }).optional(),
14
16
  });
15
17
  /**
16
18
  * A preview rebinds copied platform rows and deploys functions, so it runs only where that cannot
@@ -36,7 +38,7 @@ export function decidePreviewTarget({ envName, url, report }) {
36
38
  if (!parsed.success) {
37
39
  return { ok: false, reason: `the Atlas at ${url} sent an unrecognized local runtime report; upgrade seq-studio or that Atlas.` };
38
40
  }
39
- const { database, functions } = parsed.data;
41
+ const { database, functions, fork } = parsed.data;
40
42
  if (!database.disposable || !database.branch) {
41
43
  return {
42
44
  ok: false,
@@ -57,6 +59,7 @@ export function decidePreviewTarget({ envName, url, report }) {
57
59
  ...(database.endpoint ? { endpoint: database.endpoint } : {}),
58
60
  ...(database.name ? { name: database.name } : {}),
59
61
  },
62
+ ...(fork ? { fork: { upstreamEnvironment: fork.upstreamEnvironment, upstreamSecrets: fork.upstreamSecrets === true } } : {}),
60
63
  },
61
64
  };
62
65
  }
@@ -0,0 +1,7 @@
1
+ /** Set where the local Atlas is reached through a tunnel, so the printed link opens for the viewer. */
2
+ export declare const PREVIEW_ORIGIN_ENV = "SEQ_STUDIO_PREVIEW_ORIGIN";
3
+ /** Set where the machine's application gateway is also reached through a tunnel, so a Next.js session opens for the viewer too. */
4
+ export declare const PREVIEW_APPS_ORIGIN_ENV = "SEQ_STUDIO_PREVIEW_APPS_ORIGIN";
5
+ /** A directory of reviewed `<app id>.env` secret files, for machines provisioned to preview apps. */
6
+ export declare const PREVIEW_SECRETS_DIR_ENV = "SEQ_STUDIO_PREVIEW_SECRETS_DIR";
7
+ export declare const PREVIEW_USAGE = "usage: seq-studio preview [dir] -e local [--only <id>[,<id>...]] [--secrets <file>] [--secret-source <source>] [--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\nA directory with no sequence.app.yml is previewed from its repository's .seq/repository.yml: the\nresources declared at or under that directory, plus the namespaces, functions, processes and\nworkspaces each artifact.bundle.yml reaches, wherever the repository declares them. Before it runs,\nthe command lists what each artifact declares that it does not set up (workspaces, server secrets,\nexternal-ingress service accounts, anything no resource declares) and carries on.\n\nOn a devbox whose database is a copy of a hosted deployment's, it also adopts the workspaces each\nartifact declares from that copy (their files are not copied), admits the service identities the\ncopied project records, removes from that copy the development bindings the application no longer\ndeclares, and reads a Next.js app's server secrets from that deployment as you, into memory only,\nwhen this machine holds your token for it. Each of these is listed as it happens.\n\nBefore a Next.js session starts, the directories its bundle lists under build.source_includes are\ncopied to .artifact-includes in the app, where the hosted build mounts them.\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 --secret-source <source>\n where a Next.js app's server.secrets come from, as for seq-studio artifact dev\n (local, none). Without it, a devbox fork reads them from the deployment its\n database was copied from; anywhere else the local Atlas store is used.\n --apply-orm apply each namespace's local definition to this database copy before checking it.\n Without a sequence.app.yml, only namespaces under [dir] are applied: one pulled in\n from elsewhere in the repository is checked, and applied only when --only names it.\n --only replaces the selection: list it with what you are previewing (its summary\n line gives the exact flag).\n A namespace pinned to an ORM version this CLI's does not satisfy is applied with\n its own installed copy.\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.";
@@ -0,0 +1,57 @@
1
+ /** Set where the local Atlas is reached through a tunnel, so the printed link opens for the viewer. */
2
+ export const PREVIEW_ORIGIN_ENV = 'SEQ_STUDIO_PREVIEW_ORIGIN';
3
+ /** Set where the machine's application gateway is also reached through a tunnel, so a Next.js session opens for the viewer too. */
4
+ export const PREVIEW_APPS_ORIGIN_ENV = 'SEQ_STUDIO_PREVIEW_APPS_ORIGIN';
5
+ /** A directory of reviewed `<app id>.env` secret files, for machines provisioned to preview apps. */
6
+ export const PREVIEW_SECRETS_DIR_ENV = 'SEQ_STUDIO_PREVIEW_SECRETS_DIR';
7
+ export const PREVIEW_USAGE = `usage: seq-studio preview [dir] -e local [--only <id>[,<id>...]] [--secrets <file>] [--secret-source <source>] [--apply-orm] [--watch] [--force] [--yes] [--json]
8
+
9
+ Stand up this app on a local Atlas and print where to open it. Reads sequence.app.yml and, in
10
+ dependency order: checks each ORM namespace answers reads, deploys each function to the local
11
+ runtime, and publishes each artifact to its preview channel. By default it previews the app's
12
+ artifacts and what they depend on; --only names other primitives (a process, a function) to start.
13
+
14
+ A directory with no sequence.app.yml is previewed from its repository's .seq/repository.yml: the
15
+ resources declared at or under that directory, plus the namespaces, functions, processes and
16
+ workspaces each artifact.bundle.yml reaches, wherever the repository declares them. Before it runs,
17
+ the command lists what each artifact declares that it does not set up (workspaces, server secrets,
18
+ external-ingress service accounts, anything no resource declares) and carries on.
19
+
20
+ On a devbox whose database is a copy of a hosted deployment's, it also adopts the workspaces each
21
+ artifact declares from that copy (their files are not copied), admits the service identities the
22
+ copied project records, removes from that copy the development bindings the application no longer
23
+ declares, and reads a Next.js app's server secrets from that deployment as you, into memory only,
24
+ when this machine holds your token for it. Each of these is listed as it happens.
25
+
26
+ Before a Next.js session starts, the directories its bundle lists under build.source_includes are
27
+ copied to .artifact-includes in the app, where the hosted build mounts them.
28
+
29
+ Runs only against a local Atlas on a personal or devbox database branch. It changes that database
30
+ copy and nothing else. Only the database is a copy: a function deployed here runs with the secret
31
+ values you give it and reaches the real systems those credentials open. Declared egress is not
32
+ enforced by the local runtime. Each function's egress and secret sources are shown before it deploys.
33
+
34
+ --only <ids> preview these primitives and their dependencies instead of the artifacts
35
+ --secrets <file> reviewed dotenv file of function secret values (default: $${PREVIEW_SECRETS_DIR_ENV}/<app id>.env).
36
+ A value may use \${preview.atlas_origin}, \${preview.database.host},
37
+ \${preview.database.endpoint}, \${preview.database.name}, \${preview.database.branch}.
38
+ \${env.NAME} takes the value from that variable of this command's environment.
39
+ A secret with no value there or in this local Atlas stops the preview.
40
+ --secret-source <source>
41
+ where a Next.js app's server.secrets come from, as for seq-studio artifact dev
42
+ (local, none). Without it, a devbox fork reads them from the deployment its
43
+ database was copied from; anywhere else the local Atlas store is used.
44
+ --apply-orm apply each namespace's local definition to this database copy before checking it.
45
+ Without a sequence.app.yml, only namespaces under [dir] are applied: one pulled in
46
+ from elsewhere in the repository is checked, and applied only when --only names it.
47
+ --only replaces the selection: list it with what you are previewing (its summary
48
+ line gives the exact flag).
49
+ A namespace pinned to an ORM version this CLI's does not satisfy is applied with
50
+ its own installed copy.
51
+ --watch keep rebuilding a static artifact on change (a Next.js app always stays attached)
52
+ --force redeploy a function even when nothing it is built from changed. Needed after a
53
+ credential held in an environment variable is rotated.
54
+ --yes do not ask before deploying functions
55
+ --json print the result as JSON
56
+
57
+ Set ${PREVIEW_ORIGIN_ENV} to the URL you open the local Atlas at when that is not its own address.`;
@@ -133,7 +133,8 @@ async function listCommand() {
133
133
  }
134
134
  if (Object.keys(config.envs).every((name) => name === 'local' || name.startsWith('local:'))) {
135
135
  console.log('');
136
- console.log('Register your organization\'s deployment with: seq-studio envs add <name> <url>');
136
+ console.log('Add your organization\'s deployment by signing in to it: seq-studio login <deployment-url>');
137
+ console.log('To give it a name of your own instead: seq-studio envs add <name> <url>');
137
138
  console.log(manualEnvConfigHint());
138
139
  }
139
140
  return 0;
package/dist/login.js CHANGED
@@ -200,7 +200,7 @@ export async function login(envName) {
200
200
  // OpCo name would silently do a Sequence login otherwise, so say which
201
201
  // realm we're using.
202
202
  console.error(`'${envName}' uses the shared Sequence login ` +
203
- '(register OpCo environments with: seq-studio envs add <name> <url>).');
203
+ '(sign in to another organization\'s deployment with: seq-studio login <deployment-url>).');
204
204
  }
205
205
  await loginWithPkce({ realm });
206
206
  console.log(`Authenticated [${realm.name}]. Short-lived access token saved to ${seqapiTokenPath()}.`);
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Why the loaded ORM cannot carry `--break-glass`, or null when it can. The reason travels in an environment
3
+ * variable the ORM's own transport reads; a project's copy from before that reads nothing and would send the
4
+ * request without it, which Atlas refuses as if no reason was given.
5
+ */
6
+ export declare function breakGlassRefusal({ ormCli, version }: {
7
+ ormCli: object;
8
+ version?: string;
9
+ }): string | null;
10
+ /** Give the ORM CLI the reason the router took off argv (cli-attribution.ts). Returns why it cannot, else null. */
11
+ export declare function handOverBreakGlass({ reason, ormCli, version }: {
12
+ reason?: string;
13
+ ormCli: object;
14
+ version?: string;
15
+ }): string | null;
@@ -0,0 +1,22 @@
1
+ /** The variable the ORM CLI's transport reads the break-glass reason from; its `BREAK_GLASS_ENV` export. */
2
+ const BREAK_GLASS_ENV = 'SEQUENCE_ORM_BREAK_GLASS';
3
+ /**
4
+ * Why the loaded ORM cannot carry `--break-glass`, or null when it can. The reason travels in an environment
5
+ * variable the ORM's own transport reads; a project's copy from before that reads nothing and would send the
6
+ * request without it, which Atlas refuses as if no reason was given.
7
+ */
8
+ export function breakGlassRefusal({ ormCli, version }) {
9
+ if (Reflect.get(ormCli, 'BREAK_GLASS_ENV') === BREAK_GLASS_ENV)
10
+ return null;
11
+ return `this project's @sequenceholdings/orm${version ? ` ${version}` : ''} cannot carry --break-glass: it predates it and would send ` +
12
+ 'the request without the reason. Upgrade the project\'s @sequenceholdings/orm, or rerun with --sdk bundled.';
13
+ }
14
+ /** Give the ORM CLI the reason the router took off argv (cli-attribution.ts). Returns why it cannot, else null. */
15
+ export function handOverBreakGlass({ reason, ormCli, version }) {
16
+ if (!reason)
17
+ return null;
18
+ const refusal = breakGlassRefusal({ ormCli, version });
19
+ if (!refusal)
20
+ process.env[BREAK_GLASS_ENV] = reason;
21
+ return refusal;
22
+ }
@@ -18,6 +18,7 @@ import { REQUIRE_EXPLICIT_ENV_MESSAGE } from '../env-flags.js';
18
18
  import { resolveFunctionSourceDir } from '../functions/source-selection.js';
19
19
  import { warnBeforeHostDeploy } from '../manifest-roles-notice.js';
20
20
  import { ORM_DEPLOYMENT_POLICY_HELP, ORM_DISCOVER_HELP, ORM_EXECUTE_HELP, ORM_HELP, ORM_HISTORY_HELP } from '../command-help.js';
21
+ import { handOverBreakGlass } from './break-glass.js';
21
22
  import { ormVersionMismatch, requiresSchemaVersionCheck } from './version-guard.js';
22
23
  import { exportApplySource, exportLocalApplySource, repoOrmApplySource, resolveOrmSourceEnvironment, SOURCE_ENV_WITH_REPO_ERROR, takeApplySourceFlags, } from './apply-source.js';
23
24
  /**
@@ -131,7 +132,7 @@ async function runOrmFromRepo({ sub, selection, auth, targetUrl, ormCli, unverif
131
132
  repoDir: source.dir,
132
133
  ...(selection.path !== undefined ? { path: selection.path } : {}),
133
134
  });
134
- const mismatch = await ormVersionMismatch(dir, { loadedVersion: await loadedOrmVersion() });
135
+ const mismatch = await ormVersionMismatch(dir, await loadedOrm());
135
136
  if (mismatch)
136
137
  return failWith(mismatch);
137
138
  await aliasOrmModuleForRemoteSource(ormCli.ORM_MODULE_PATH_ENV);
@@ -157,9 +158,10 @@ async function runOrmFromRepo({ sub, selection, auth, targetUrl, ormCli, unverif
157
158
  await source.cleanup();
158
159
  }
159
160
  }
160
- /** The ORM version loadOrmCli loaded: the project's under `sdk: project`, else the bundled one. */
161
- async function loadedOrmVersion() {
162
- return (await import('../sdk-source.js')).selectedSdkVersion('@sequenceholdings/orm');
161
+ /** The ORM loadOrmCli loaded (the project's under `sdk: project`, else the bundled one) and whether the project's was asked for. */
162
+ async function loadedOrm() {
163
+ const { selectedSdkVersion, projectSdkRequested } = await import('../sdk-source.js');
164
+ return { loadedVersion: selectedSdkVersion('@sequenceholdings/orm'), projectRequested: projectSdkRequested('@sequenceholdings/orm') };
163
165
  }
164
166
  /** `cwd` is the project whose installed ORM and .seq/github.yml decide the copy; the current directory by default. */
165
167
  async function loadOrmCli({ cwd } = {}) {
@@ -331,9 +333,9 @@ export async function runOrmCommand(sub, rest) {
331
333
  return 1;
332
334
  const { runCli, setTokenProvider } = ormCli;
333
335
  // The ORM CLI has its own transport: hand it --break-glass, which the router took off argv (cli-attribution.ts).
334
- const breakGlass = cliAttributionHeaders()[BREAK_GLASS_HEADER];
335
- if (breakGlass)
336
- process.env['SEQUENCE_ORM_BREAK_GLASS'] = breakGlass;
336
+ const refusal = handOverBreakGlass({ reason: cliAttributionHeaders()[BREAK_GLASS_HEADER], ormCli, version: (await loadedOrm()).loadedVersion });
337
+ if (refusal)
338
+ return failWith(refusal);
337
339
  setTokenProvider(async () => {
338
340
  try {
339
341
  return await getAccessToken({ env: authEnv, targetUrl });
@@ -351,7 +353,7 @@ async function runLocalOrm({ sub, normalized, auth, targetUrl, unverifiedReason,
351
353
  const sourceEnvironment = sourceEnv ? await resolveOrmSourceEnvironment({ requested: sourceEnv }) : undefined;
352
354
  if (sourceEnvironment && 'error' in sourceEnvironment)
353
355
  return failWith(sourceEnvironment.error);
354
- const problem = (requiresSchemaVersionCheck(sub) ? await ormVersionMismatch(positionalDir(normalized) ?? '.', { loadedVersion: await loadedOrmVersion() }) : null) ??
356
+ const problem = (requiresSchemaVersionCheck(sub) ? await ormVersionMismatch(positionalDir(normalized) ?? '.', await loadedOrm()) : null) ??
355
357
  await exportLocalApplySource({ sub, auth, targetUrl, dir: positionalDir(normalized), unverifiedReason, sourceEnvironment, dryRun: normalized.includes('--dry-run') });
356
358
  if (problem)
357
359
  return failWith(problem);
@@ -1,8 +1,12 @@
1
1
  export declare function requiresSchemaVersionCheck(sub: string): boolean;
2
+ /** The valid ORM range a v2 namespace pins, or null: a caller choosing which ORM to load has nothing to satisfy. */
3
+ export declare function pinnedOrmRange(dir: string): Promise<string | null>;
2
4
  /**
3
5
  * Fail before compiling a v2 schema with an ORM outside its declared range. `loadedVersion` is the ORM this command
4
- * runs (the project's under `sdk: project`); without it, the copy beside this CLI.
6
+ * runs (the project's under `sdk: project`); without it, the copy beside this CLI. `projectRequested` says the
7
+ * command already ran with `sdk: project`, so the remedy is the namespace's install and not that flag again.
5
8
  */
6
- export declare function ormVersionMismatch(dir: string, { loadedVersion }?: {
9
+ export declare function ormVersionMismatch(dir: string, { loadedVersion, projectRequested }?: {
7
10
  loadedVersion?: string;
11
+ projectRequested?: boolean;
8
12
  }): Promise<string | null>;
@@ -22,11 +22,8 @@ function dependencyRange(manifest) {
22
22
  }
23
23
  return undefined;
24
24
  }
25
- /**
26
- * Fail before compiling a v2 schema with an ORM outside its declared range. `loadedVersion` is the ORM this command
27
- * runs (the project's under `sdk: project`); without it, the copy beside this CLI.
28
- */
29
- export async function ormVersionMismatch(dir, { loadedVersion } = {}) {
25
+ /** The `@sequenceholdings/orm` range a v2 namespace's package.json declares, or null when it declares none to check. */
26
+ async function declaredOrmRange(dir) {
30
27
  const configPath = join(resolve(dir), 'sequence.config.ts');
31
28
  try {
32
29
  await readFile(configPath);
@@ -49,14 +46,37 @@ export async function ormVersionMismatch(dir, { loadedVersion } = {}) {
49
46
  const range = dependencyRange(manifest);
50
47
  if (range === undefined || (typeof range === 'string' && range.startsWith('workspace:')))
51
48
  return null;
49
+ return { range, manifestPath };
50
+ }
51
+ /** The valid ORM range a v2 namespace pins, or null: a caller choosing which ORM to load has nothing to satisfy. */
52
+ export async function pinnedOrmRange(dir) {
53
+ const declared = await declaredOrmRange(dir);
54
+ return typeof declared?.range === 'string' && validRange(declared.range) ? declared.range : null;
55
+ }
56
+ /**
57
+ * Fail before compiling a v2 schema with an ORM outside its declared range. `loadedVersion` is the ORM this command
58
+ * runs (the project's under `sdk: project`); without it, the copy beside this CLI. `projectRequested` says the
59
+ * command already ran with `sdk: project`, so the remedy is the namespace's install and not that flag again.
60
+ */
61
+ export async function ormVersionMismatch(dir, { loadedVersion, projectRequested = false } = {}) {
62
+ const declared = await declaredOrmRange(dir);
63
+ if (declared === null)
64
+ return null;
65
+ const { range, manifestPath } = declared;
52
66
  if (typeof range !== 'string' || !validRange(range)) {
53
67
  return `invalid @sequenceholdings/orm range "${String(range)}" in ${manifestPath}`;
54
68
  }
55
69
  const version = loadedVersion ?? await bundledOrmVersion();
56
70
  if (typeof version !== 'string' || !satisfies(version, range)) {
57
71
  return `this seq-studio loads @sequenceholdings/orm ${typeof version === 'string' ? version : '(unknown version)'}, ` +
58
- `but ${manifestPath} requires ${range}. Run the namespace-local CLI after installing its dependencies, ` +
59
- 'or upgrade seq-studio and @sequenceholdings/orm together.';
72
+ `but ${manifestPath} requires ${range}. ` +
73
+ (projectRequested
74
+ // Already asked for the project's copy: it is installed outside the range, or could not be used and the
75
+ // bundled one ran (a warning above says which).
76
+ ? `sdk: project is already selected, so the copy installed for this namespace is not one ${range} accepts. ` +
77
+ `Reinstall the namespace's dependencies (pnpm install in ${resolve(dir)}), `
78
+ : 'Install the namespace\'s dependencies and rerun with --sdk project to load its own @sequenceholdings/orm, ') +
79
+ 'run the namespace-local CLI after installing its dependencies, or upgrade seq-studio and @sequenceholdings/orm together.';
60
80
  }
61
81
  return null;
62
82
  }
@@ -7,17 +7,16 @@ const GROUP_TITLES = {
7
7
  cli: 'This CLI',
8
8
  };
9
9
  const FOOTER = `
10
- Authenticate with: seq-studio login
11
- init, orm init, functions init, artifact init, and agents init take
12
- --repo <ns>/<name> to scaffold straight into a git-service repo; commit and push from there.
10
+ Sign in once with a deployment's URL: seq-studio login <deployment-url>. After that,
11
+ -e <org>/staging and -e <org>/prod reach its org from anywhere, and inside a repository
12
+ set up with seq-studio repo init, -e staging and -e prod mean that repository's org.
13
13
  In an agent sandbox, SEQ_STUDIO_BASE_URL + SEQ_STUDIO_TOKEN_FILE select the
14
14
  deployment and token instead (no login; -e optional).
15
15
  --json writes only JSON to stdout (status lines go to stderr); objects carry
16
16
  "schema": "<command>@<n>". Exit codes: 0 ok, 1 failed, 2 usage, 3 blocked, 4 auth.
17
- Built-in env: local. Add your organization's deployment with
18
- \`seq-studio envs add <name> <url>\`; custom entries live in ~/.config/seq-studio/config.toml.
17
+ Config lives in ~/.config/seq-studio/; seq-studio envs list prints each environment URL.
19
18
  If this CLI cannot complete a documented step, read that environment's docs
20
- before trying another tool. \`seq-studio envs list\` prints each environment URL.
19
+ before trying another tool.
21
20
  Docs: seq-studio docs search <query> -e <env>, or <url>/docs. Feedback guide: <url>/docs/raw/seq-studio/feedback.md.
22
21
  `;
23
22
  export function showsInternal(env = process.env) {