@sequenceholdings/studio-cli 0.9.24 → 0.9.26

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 (40) hide show
  1. package/README.md +14 -2
  2. package/dist/app-preview/commands.d.ts +7 -0
  3. package/dist/app-preview/commands.js +264 -0
  4. package/dist/app-preview/fingerprint.d.ts +20 -0
  5. package/dist/app-preview/fingerprint.js +32 -0
  6. package/dist/app-preview/install.d.ts +31 -0
  7. package/dist/app-preview/install.js +53 -0
  8. package/dist/app-preview/namespace-probe.d.ts +13 -0
  9. package/dist/app-preview/namespace-probe.js +50 -0
  10. package/dist/app-preview/plan.d.ts +28 -0
  11. package/dist/app-preview/plan.js +41 -0
  12. package/dist/app-preview/run.d.ts +32 -0
  13. package/dist/app-preview/run.js +48 -0
  14. package/dist/app-preview/runners.d.ts +73 -0
  15. package/dist/app-preview/runners.js +226 -0
  16. package/dist/app-preview/secrets.d.ts +48 -0
  17. package/dist/app-preview/secrets.js +104 -0
  18. package/dist/app-preview/target.d.ts +28 -0
  19. package/dist/app-preview/target.js +62 -0
  20. package/dist/artifact/delegate.d.ts +0 -11
  21. package/dist/artifact/delegate.js +6 -127
  22. package/dist/artifact/sandbox.js +1 -1
  23. package/dist/auth.js +1 -3
  24. package/dist/command-help.d.ts +3 -3
  25. package/dist/command-help.js +7 -3
  26. package/dist/config.d.ts +0 -7
  27. package/dist/config.js +0 -12
  28. package/dist/edge-auth-headers.js +1 -18
  29. package/dist/functions/commands.d.ts +15 -0
  30. package/dist/functions/commands.js +67 -11
  31. package/dist/main.js +1 -1
  32. package/dist/registry/lifecycle-commands.js +7 -0
  33. package/dist/repos/commands.d.ts +1 -4
  34. package/dist/repos/commands.js +2 -19
  35. package/dist/templates/catalog.d.ts +1 -1
  36. package/dist/templates/catalog.js +1 -1
  37. package/package.json +10 -10
  38. package/release-summary.json +3 -1
  39. package/dist/preview.d.ts +0 -90
  40. package/dist/preview.js +0 -292
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Run the plan in order. A primitive whose dependency failed is skipped, not attempted: a UI
3
+ * published over a function that did not deploy would look like a working preview and is not one.
4
+ * A dependency this command cannot preview does not block its dependents, but stays in the result
5
+ * so the summary says what the preview is missing.
6
+ */
7
+ export async function runPreviewPlan({ plan, run }) {
8
+ const results = [];
9
+ const blocked = new Set();
10
+ for (const step of plan.steps) {
11
+ const { entry } = step;
12
+ const base = { id: entry.id, kind: entry.kind };
13
+ const blocker = entry.depends_on.find((id) => blocked.has(id));
14
+ if (blocker) {
15
+ blocked.add(entry.id);
16
+ results.push({ ...base, status: 'skipped', detail: `not attempted: ${blocker} is not ready` });
17
+ continue;
18
+ }
19
+ if (step.action === 'unsupported') {
20
+ results.push({ ...base, status: 'unsupported', detail: step.reason });
21
+ continue;
22
+ }
23
+ let outcome;
24
+ try {
25
+ outcome = await run(step);
26
+ }
27
+ catch (error) {
28
+ const message = error instanceof Error ? error.message : String(error);
29
+ // The whole message goes to the terminal; the summary keeps the line that names the problem.
30
+ if (message.includes('\n'))
31
+ console.error(message);
32
+ outcome = { status: 'failed', detail: headline(message) };
33
+ }
34
+ if (outcome.status === 'failed')
35
+ blocked.add(entry.id);
36
+ results.push({ ...base, ...outcome });
37
+ }
38
+ return results;
39
+ }
40
+ /** One line of a possibly multi-line error: the first that reads as the error itself, not a runtime warning or a stack frame. */
41
+ export function headline(message) {
42
+ const lines = message.split('\n').map((line) => line.trim()).filter(Boolean);
43
+ const informative = lines.filter((line) => !line.startsWith('at ') && !/^\(node:\d+\)/.test(line) && !line.startsWith('(Use `node'));
44
+ return informative.find((line) => /^error\b/i.test(line)) ?? informative[0] ?? lines[0] ?? 'failed with no message';
45
+ }
46
+ export function previewSucceeded(results) {
47
+ return results.every((result) => result.status === 'ready' || result.status === 'unsupported');
48
+ }
@@ -0,0 +1,73 @@
1
+ import type { PrimitiveEntry } from '../app/manifest.js';
2
+ import { type SecretPlan } from './secrets.js';
3
+ import type { StepOutcome } from './run.js';
4
+ import type { PreviewTarget } from './target.js';
5
+ export interface PreviewContext {
6
+ rootDir: string;
7
+ env: string;
8
+ client: {
9
+ baseUrl: string;
10
+ token: string;
11
+ };
12
+ target: PreviewTarget;
13
+ /** The origin a person opens. Differs from the Atlas origin behind a tunnel. */
14
+ publicOrigin: string;
15
+ }
16
+ export declare const primitiveDir: ({ ctx, entry }: {
17
+ ctx: PreviewContext;
18
+ entry: PrimitiveEntry;
19
+ }) => Promise<string>;
20
+ export declare function checkNamespace({ ctx, entry, apply }: {
21
+ ctx: PreviewContext;
22
+ entry: PrimitiveEntry;
23
+ apply: boolean;
24
+ }): Promise<StepOutcome>;
25
+ export interface FunctionInspection {
26
+ entry: PrimitiveEntry;
27
+ slug: string;
28
+ egress: string[];
29
+ secrets: SecretPlan;
30
+ /** Key/value sets the function maps entries from; a preview cannot supply these. */
31
+ unavailableSets: string[];
32
+ }
33
+ /** Read what a function will be able to reach and where its secrets come from, before anything deploys. */
34
+ export declare function inspectFunction({ ctx, entry, provided, providedFile }: {
35
+ ctx: PreviewContext;
36
+ entry: PrimitiveEntry;
37
+ provided: Record<string, string>;
38
+ providedFile: string | null;
39
+ }): Promise<FunctionInspection>;
40
+ export declare function deployFunction({ ctx, inspection, force }: {
41
+ ctx: PreviewContext;
42
+ inspection: FunctionInspection;
43
+ force: boolean;
44
+ }): Promise<StepOutcome>;
45
+ export interface ArtifactInspection {
46
+ entry: PrimitiveEntry;
47
+ dir: string;
48
+ projectId: string;
49
+ nextjs: boolean;
50
+ }
51
+ export declare function inspectArtifact({ ctx, entry }: {
52
+ ctx: PreviewContext;
53
+ entry: PrimitiveEntry;
54
+ }): Promise<ArtifactInspection>;
55
+ /** Install a fresh clone's dependencies. Returns a failure outcome, or undefined when the artifact can build. */
56
+ export declare function ensureArtifactDependencies({ ctx, inspection }: {
57
+ ctx: PreviewContext;
58
+ inspection: ArtifactInspection;
59
+ }): Promise<StepOutcome | undefined>;
60
+ /** The preview key a bare preview URL shows, so the link works with no query string to lose. */
61
+ export declare const DEFAULT_PREVIEW_KEY = "default";
62
+ export declare function staticPreviewUrl({ origin, projectId }: {
63
+ origin: string;
64
+ projectId: string;
65
+ }): string;
66
+ export declare function publishStaticArtifact({ ctx, inspection }: {
67
+ ctx: PreviewContext;
68
+ inspection: ArtifactInspection;
69
+ }): Promise<StepOutcome>;
70
+ export declare function applyProcess({ ctx, entry }: {
71
+ ctx: PreviewContext;
72
+ entry: PrimitiveEntry;
73
+ }): Promise<StepOutcome>;
@@ -0,0 +1,226 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { chmod, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { parse as parseYaml } from 'yaml';
6
+ import { getJson, getJsonOr404, postJsonResponse } from '../atlas-client.js';
7
+ import { resolveContainedPrimitivePath } from '../app/paths.js';
8
+ import { schemaViewSchema } from '../orm/discover-schema.js';
9
+ import { fingerprintMessage, fingerprintOf, functionFingerprint } from './fingerprint.js';
10
+ import { decideInstall, installDependencies } from './install.js';
11
+ import { interpretNamespaceProbe } from './namespace-probe.js';
12
+ import { planFunctionSecrets, secretsEnvFile } from './secrets.js';
13
+ export const primitiveDir = ({ ctx, entry }) => resolveContainedPrimitivePath({ rootDir: ctx.rootDir, entryPath: entry.path });
14
+ const quoted = (identifier) => `"${identifier.replaceAll('"', '""')}"`;
15
+ export async function checkNamespace({ ctx, entry, apply }) {
16
+ const namespace = entry.namespace;
17
+ 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}` };
22
+ }
23
+ const schemaBody = await getJsonOr404({
24
+ ...ctx.client,
25
+ path: `/api/orm/namespaces/${encodeURIComponent(namespace)}/schema`,
26
+ });
27
+ if (schemaBody === null)
28
+ return interpretNamespaceProbe({ namespace, status: 404, body: null });
29
+ 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') {
32
+ return { status: 'ready', detail: `namespace ${namespace} is registered and has no tables to read` };
33
+ }
34
+ const { createOperationExecutorWithTransport } = await import('@sequenceholdings/orm/client');
35
+ let seen = { status: 0, body: null };
36
+ const executor = createOperationExecutorWithTransport({
37
+ namespace,
38
+ transport: async ({ namespace: target, op, variables, expectedKind }) => {
39
+ const response = await postJsonResponse({ ...ctx.client, path: `/api/data/v2/${target}`, body: { op, variables, expectedKind } });
40
+ let body = null;
41
+ try {
42
+ body = JSON.parse(response.body);
43
+ }
44
+ catch {
45
+ body = null;
46
+ }
47
+ seen = { status: response.status, body };
48
+ return { ok: response.status >= 200 && response.status < 300, status: response.status, body };
49
+ },
50
+ });
51
+ // A local Atlas repairs a missing owner-role membership when it next resolves the owner, which
52
+ // 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;
60
+ }
61
+ if (seen.status !== 500)
62
+ break;
63
+ }
64
+ return interpretNamespaceProbe({ namespace, ...seen });
65
+ }
66
+ /** Read what a function will be able to reach and where its secrets come from, before anything deploys. */
67
+ export async function inspectFunction({ ctx, entry, provided, providedFile }) {
68
+ const { readManifestOptional } = await import('../functions/commands.js');
69
+ const dir = await primitiveDir({ ctx, entry });
70
+ const manifest = await readManifestOptional(dir);
71
+ if (!manifest)
72
+ throw new Error(`${entry.id}: no managed-function.yml in ${dir}`);
73
+ const { secrets: stored } = await getJson({ ...ctx.client, path: '/api/managed-secrets' });
74
+ const storedLocally = new Set(stored.filter((secret) => secret.hasDefaultValue).map((secret) => secret.name));
75
+ const single = manifest.secrets.filter((secret) => typeof secret === 'string');
76
+ const sets = manifest.secrets.flatMap((secret) => (typeof secret === 'string' ? [] : [secret.secret]));
77
+ return {
78
+ entry,
79
+ slug: manifest.function.id,
80
+ egress: [...manifest.egress],
81
+ secrets: planFunctionSecrets({ declared: single, provided, providedFile, storedLocally, target: ctx.target }),
82
+ unavailableSets: sets.filter((name) => !storedLocally.has(name)),
83
+ };
84
+ }
85
+ /**
86
+ * The files a deploy of this function would upload. A function that imports the app's workspace
87
+ * packages is compiled together with them first, so an edit to a shared package changes this set
88
+ * even when nothing in the function's own directory did.
89
+ */
90
+ async function deployedBundleFiles(dir) {
91
+ const { collectBundleFiles } = await import('../functions/bundle.js');
92
+ const { prepareFunctionWorkspace } = await import('../functions/workspace.js');
93
+ const prepared = await prepareFunctionWorkspace({ dir });
94
+ try {
95
+ return (await collectBundleFiles(prepared.dir)).files;
96
+ }
97
+ finally {
98
+ await prepared.cleanup();
99
+ }
100
+ }
101
+ /** The fingerprint of the active version when this function is already deployed here, else undefined. */
102
+ async function deployedFingerprint({ ctx, slug }) {
103
+ const { functions } = await getJson({
104
+ ...ctx.client,
105
+ path: `/api/managed-functions?slug=${encodeURIComponent(slug)}`,
106
+ });
107
+ const fn = functions.find((candidate) => candidate.slug === slug);
108
+ if (!fn?.deployed || fn.secretsNeedDeploy)
109
+ return undefined;
110
+ const versions = await getJsonOr404({
111
+ ...ctx.client,
112
+ path: `/api/managed-functions/${fn.id}/versions`,
113
+ });
114
+ const active = versions?.versions.find((version) => version.isActive && version.status === 'deployed');
115
+ return fingerprintOf(active?.deployMessage);
116
+ }
117
+ /**
118
+ * True when Atlas confirms the function's runtime is this workspace's. Asked through adoption,
119
+ * which changes nothing for a function already bound here; when it does have to adopt, the
120
+ * function has no active version and must be deployed.
121
+ */
122
+ async function ownedHere({ ctx, slug }) {
123
+ const { functions } = await getJson({
124
+ ...ctx.client,
125
+ path: `/api/managed-functions?slug=${encodeURIComponent(slug)}`,
126
+ });
127
+ const fn = functions.find((candidate) => candidate.slug === slug);
128
+ if (!fn)
129
+ return false;
130
+ const { postJson } = await import('../atlas-client.js');
131
+ const result = await postJson({ ...ctx.client, path: `/api/managed-functions/${fn.id}/local-adoption` });
132
+ return result.adopted === false;
133
+ }
134
+ export async function deployFunction({ ctx, inspection, force }) {
135
+ const { functionsDeployCommand } = await import('../functions/commands.js');
136
+ const dir = await primitiveDir({ ctx, entry: inspection.entry });
137
+ const files = await deployedBundleFiles(dir);
138
+ const fingerprint = functionFingerprint({ files, sources: inspection.secrets.sources, values: inspection.secrets.values });
139
+ // A matching fingerprint only proves what was deployed, not where. A database copied from
140
+ // another preview carries the same message while its runtime lives elsewhere, so the shortcut
141
+ // also needs Atlas to say this workspace already owns the function.
142
+ if (!force && (await deployedFingerprint({ ctx, slug: inspection.slug })) === fingerprint && (await ownedHere({ ctx, slug: inspection.slug }))) {
143
+ return { status: 'ready', detail: `function ${inspection.slug} is unchanged since the last preview deployed it (--force to redeploy)` };
144
+ }
145
+ // Values reach the deploy as a private file, never as arguments another process could list.
146
+ const scratch = await mkdtemp(join(tmpdir(), 'seq-preview-'));
147
+ const envFile = join(scratch, 'secrets.env');
148
+ try {
149
+ await writeFile(envFile, secretsEnvFile(inspection.secrets.values), { mode: 0o600 });
150
+ await chmod(envFile, 0o600);
151
+ const code = await functionsDeployCommand({
152
+ positional: [],
153
+ flags: { dir, env: ctx.env, yes: true, adopt: true, 'from-env-file': envFile, message: fingerprintMessage(fingerprint) },
154
+ });
155
+ return code === 0
156
+ ? { status: 'ready', detail: `function ${inspection.slug} is deployed to this Atlas's local runtime` }
157
+ : { status: 'failed', detail: `seq-studio function deploy for ${inspection.slug} exited ${code}; its output above says why` };
158
+ }
159
+ finally {
160
+ await rm(scratch, { recursive: true, force: true });
161
+ }
162
+ }
163
+ export async function inspectArtifact({ ctx, entry }) {
164
+ const dir = await primitiveDir({ ctx, entry });
165
+ const path = join(dir, 'artifact.bundle.yml');
166
+ if (!existsSync(path))
167
+ throw new Error(`${entry.id}: no artifact.bundle.yml in ${dir}`);
168
+ const raw = parseYaml(await readFile(path, 'utf8'));
169
+ const artifact = typeof raw === 'object' && raw !== null ? Reflect.get(raw, 'artifact') : undefined;
170
+ const type = typeof artifact === 'object' && artifact !== null ? Reflect.get(artifact, 'type') : undefined;
171
+ return { entry, dir, projectId: entry.project_id, nextjs: type === 'nextjs' };
172
+ }
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 });
176
+ if (!decision.install)
177
+ return undefined;
178
+ console.error(`[seq-studio] installing dependencies for ${inspection.projectId}: pnpm ${decision.args.join(' ')} (in ${decision.root})`);
179
+ const code = await installDependencies(decision);
180
+ return code === 0
181
+ ? undefined
182
+ : { status: 'failed', detail: `pnpm ${decision.args.join(' ')} in ${decision.root} exited ${code}; the artifact cannot build without its dependencies` };
183
+ }
184
+ /** The preview key a bare preview URL shows, so the link works with no query string to lose. */
185
+ export const DEFAULT_PREVIEW_KEY = 'default';
186
+ export function staticPreviewUrl({ origin, projectId }) {
187
+ return `${origin}/artifact-studio/projects/${encodeURIComponent(projectId)}/preview?key=${DEFAULT_PREVIEW_KEY}`;
188
+ }
189
+ export async function publishStaticArtifact({ ctx, inspection }) {
190
+ const installed = await ensureArtifactDependencies({ ctx, inspection });
191
+ if (installed)
192
+ return installed;
193
+ const { runArtifactCommand } = await import('../artifact/delegate.js');
194
+ const code = await runArtifactCommand('dev', [inspection.dir, '--env', ctx.env, '--once', '--key', DEFAULT_PREVIEW_KEY]);
195
+ if (code !== 0) {
196
+ return { status: 'failed', detail: `seq-studio artifact dev for ${inspection.projectId} exited ${code}; its output above says why` };
197
+ }
198
+ // The page is addressed by the project's id, which only Atlas knows; the manifest carries its slug.
199
+ const { projects } = await getJson({
200
+ ...ctx.client,
201
+ path: `/api/artifact-studio/projects?slug=${encodeURIComponent(inspection.projectId)}`,
202
+ });
203
+ const project = projects.find((candidate) => candidate.slug === inspection.projectId);
204
+ if (!project) {
205
+ return { status: 'failed', detail: `artifact ${inspection.projectId} was published, but this Atlas lists no project with that slug to link to` };
206
+ }
207
+ return {
208
+ status: 'ready',
209
+ detail: `artifact ${inspection.projectId} is published to its preview channel`,
210
+ url: staticPreviewUrl({ origin: ctx.publicOrigin, projectId: project.id }),
211
+ };
212
+ }
213
+ export async function applyProcess({ ctx, entry }) {
214
+ const { applyCommand } = await import('../process/commands.js');
215
+ const code = await applyCommand({
216
+ positional: [],
217
+ flags: {
218
+ dir: await primitiveDir({ ctx, entry }),
219
+ env: ctx.env,
220
+ ...(entry.only?.length ? { only: entry.only.join(',') } : {}),
221
+ },
222
+ });
223
+ return code === 0
224
+ ? { status: 'ready', detail: `process ${entry.id} is registered on this Atlas; no run was started` }
225
+ : { status: 'failed', detail: `seq-studio process apply for ${entry.id} exited ${code}` };
226
+ }
@@ -0,0 +1,48 @@
1
+ import type { PreviewTarget } from './target.js';
2
+ /** Where a preview takes one declared function secret from. Never the value itself. */
3
+ export type SecretSource = {
4
+ name: string;
5
+ source: 'derived';
6
+ from: string;
7
+ } | {
8
+ name: string;
9
+ source: 'provided';
10
+ file: string;
11
+ } | {
12
+ name: string;
13
+ source: 'environment';
14
+ variables: string[];
15
+ file: string;
16
+ } | {
17
+ name: string;
18
+ source: 'local-store';
19
+ } | {
20
+ name: string;
21
+ source: 'missing';
22
+ unset?: string[];
23
+ };
24
+ export interface SecretPlan {
25
+ sources: SecretSource[];
26
+ /** Values to write for this deploy: derived and provided ones only. */
27
+ values: Record<string, string>;
28
+ missing: string[];
29
+ }
30
+ /** Facts about this preview a secret value may be built from. Nothing here is a credential. */
31
+ export declare function previewFacts(target: PreviewTarget): Record<string, string | undefined>;
32
+ /**
33
+ * Decide each declared secret's source, in this order: the reviewed secrets file, then a value
34
+ * already stored in this local Atlas. There is no third source. A value copied by a database fork
35
+ * points at another runtime's secret, which a preview cannot and must not read, and a preview
36
+ * never substitutes some other credential the machine happens to hold.
37
+ */
38
+ export declare function planFunctionSecrets({ declared, provided, providedFile, storedLocally, target, environment }: {
39
+ declared: readonly string[];
40
+ provided: Record<string, string>;
41
+ providedFile: string | null;
42
+ storedLocally: ReadonlySet<string>;
43
+ target: PreviewTarget;
44
+ environment?: Record<string, string | undefined>;
45
+ }): SecretPlan;
46
+ export declare function describeSecretSource(source: SecretSource): string;
47
+ /** Dotenv text for the values this deploy writes. Single-quoted so nothing is expanded on read. */
48
+ export declare function secretsEnvFile(values: Record<string, string>): string;
@@ -0,0 +1,104 @@
1
+ const PLACEHOLDER = /\$\{preview\.([a-z_.]+)\}/g;
2
+ /** `${env.NAME}`: the file names which variable of the command's own environment holds the value. */
3
+ const ENVIRONMENT = /\$\{env\.([A-Za-z_][A-Za-z0-9_]*)\}/g;
4
+ /** Facts about this preview a secret value may be built from. Nothing here is a credential. */
5
+ export function previewFacts(target) {
6
+ return {
7
+ atlas_origin: target.origin,
8
+ 'database.host': target.database.host,
9
+ 'database.endpoint': target.database.endpoint,
10
+ 'database.name': target.database.name,
11
+ 'database.branch': target.database.branch,
12
+ };
13
+ }
14
+ function expand({ raw, facts }) {
15
+ const used = [];
16
+ const unknown = [];
17
+ const value = raw.replace(PLACEHOLDER, (match, key) => {
18
+ const fact = facts[key];
19
+ if (fact === undefined) {
20
+ unknown.push(key);
21
+ return match;
22
+ }
23
+ used.push(key);
24
+ return fact;
25
+ });
26
+ return { value, used, unknown };
27
+ }
28
+ /**
29
+ * Decide each declared secret's source, in this order: the reviewed secrets file, then a value
30
+ * already stored in this local Atlas. There is no third source. A value copied by a database fork
31
+ * points at another runtime's secret, which a preview cannot and must not read, and a preview
32
+ * never substitutes some other credential the machine happens to hold.
33
+ */
34
+ export function planFunctionSecrets({ declared, provided, providedFile, storedLocally, target, environment = process.env }) {
35
+ const facts = previewFacts(target);
36
+ const sources = [];
37
+ const values = {};
38
+ const missing = [];
39
+ for (const name of new Set(declared)) {
40
+ const raw = provided[name];
41
+ if (raw !== undefined && raw.length > 0 && providedFile) {
42
+ const variables = [];
43
+ const unset = [];
44
+ const withEnvironment = raw.replace(ENVIRONMENT, (_match, variable) => {
45
+ const held = environment[variable];
46
+ if (held === undefined || held.length === 0)
47
+ unset.push(variable);
48
+ else
49
+ variables.push(variable);
50
+ return held ?? '';
51
+ });
52
+ if (unset.length > 0) {
53
+ // The file names a source this run does not have. That is a missing value, not a reason to look elsewhere.
54
+ sources.push({ name, source: 'missing', unset });
55
+ missing.push(name);
56
+ continue;
57
+ }
58
+ const { value, used, unknown } = expand({ raw: withEnvironment, facts });
59
+ if (unknown.length > 0) {
60
+ throw new Error(`${name} in ${providedFile} uses \${preview.${unknown[0]}}, which this preview cannot supply. ` +
61
+ `Available: ${Object.keys(facts).filter((key) => facts[key] !== undefined).map((key) => `\${preview.${key}}`).join(', ')}`);
62
+ }
63
+ values[name] = value;
64
+ if (variables.length > 0) {
65
+ sources.push({ name, source: 'environment', variables, file: providedFile });
66
+ continue;
67
+ }
68
+ sources.push(used.length > 0 && raw.replace(PLACEHOLDER, '').length === 0
69
+ ? { name, source: 'derived', from: used.map((key) => `preview.${key}`).join(' + ') }
70
+ : { name, source: 'provided', file: providedFile });
71
+ }
72
+ else if (storedLocally.has(name)) {
73
+ sources.push({ name, source: 'local-store' });
74
+ }
75
+ else {
76
+ sources.push({ name, source: 'missing' });
77
+ missing.push(name);
78
+ }
79
+ }
80
+ return { sources, values, missing };
81
+ }
82
+ export function describeSecretSource(source) {
83
+ switch (source.source) {
84
+ case 'derived':
85
+ return `derived from this preview (${source.from})`;
86
+ case 'provided':
87
+ return `from ${source.file}`;
88
+ case 'local-store':
89
+ return 'already stored in this local Atlas';
90
+ case 'environment':
91
+ return `from this command's environment (${source.variables.join(', ')}), as ${source.file} directs`;
92
+ case 'missing':
93
+ return source.unset?.length ? `NO VALUE: ${source.unset.join(', ')} is not set in this command's environment` : 'NO VALUE';
94
+ }
95
+ }
96
+ /** Dotenv text for the values this deploy writes. Single-quoted so nothing is expanded on read. */
97
+ export function secretsEnvFile(values) {
98
+ for (const [name, value] of Object.entries(values)) {
99
+ if (/[\r\n']/.test(value)) {
100
+ throw new Error(`${name} contains a quote or line break, which a preview secrets file cannot carry.`);
101
+ }
102
+ }
103
+ return Object.entries(values).map(([name, value]) => `${name}='${value}'\n`).join('');
104
+ }
@@ -0,0 +1,28 @@
1
+ export interface PreviewTarget {
2
+ origin: string;
3
+ database: {
4
+ branch: string;
5
+ host?: string;
6
+ endpoint?: string;
7
+ name?: string;
8
+ };
9
+ }
10
+ export type PreviewTargetDecision = {
11
+ ok: true;
12
+ target: PreviewTarget;
13
+ } | {
14
+ ok: false;
15
+ reason: string;
16
+ };
17
+ /**
18
+ * A preview rebinds copied platform rows and deploys functions, so it runs only where that cannot
19
+ * touch anyone else: a local Atlas whose database is a personal or devbox branch. Both halves are
20
+ * required, and the second comes from Atlas, not from this machine's configuration.
21
+ *
22
+ * `report` is what the local Atlas says about itself, or null when it did not answer as one.
23
+ */
24
+ export declare function decidePreviewTarget({ envName, url, report }: {
25
+ envName: string;
26
+ url: string;
27
+ report: unknown;
28
+ }): PreviewTargetDecision;
@@ -0,0 +1,62 @@
1
+ import { z } from 'zod';
2
+ import { isLoopbackUrl } from '../host-token.js';
3
+ const localRuntimeReportSchema = z.looseObject({
4
+ local: z.literal(true),
5
+ database: z.looseObject({
6
+ branch: z.string().nullable(),
7
+ disposable: z.boolean(),
8
+ reason: z.string().optional(),
9
+ host: z.string().optional(),
10
+ endpoint: z.string().optional(),
11
+ name: z.string().optional(),
12
+ }),
13
+ functions: z.looseObject({ localRuntime: z.boolean() }),
14
+ });
15
+ /**
16
+ * A preview rebinds copied platform rows and deploys functions, so it runs only where that cannot
17
+ * touch anyone else: a local Atlas whose database is a personal or devbox branch. Both halves are
18
+ * required, and the second comes from Atlas, not from this machine's configuration.
19
+ *
20
+ * `report` is what the local Atlas says about itself, or null when it did not answer as one.
21
+ */
22
+ export function decidePreviewTarget({ envName, url, report }) {
23
+ if (!isLoopbackUrl(url)) {
24
+ return {
25
+ ok: false,
26
+ reason: `preview runs only against a local Atlas, and ${envName} is not one. Use -e local on the machine running it.`,
27
+ };
28
+ }
29
+ if (report === null) {
30
+ return {
31
+ ok: false,
32
+ reason: `the Atlas at ${url} did not identify itself as a local development Atlas, so preview will not change anything there.`,
33
+ };
34
+ }
35
+ const parsed = localRuntimeReportSchema.safeParse(report);
36
+ if (!parsed.success) {
37
+ return { ok: false, reason: `the Atlas at ${url} sent an unrecognized local runtime report; upgrade seq-studio or that Atlas.` };
38
+ }
39
+ const { database, functions } = parsed.data;
40
+ if (!database.disposable || !database.branch) {
41
+ return {
42
+ ok: false,
43
+ reason: `${database.reason ?? 'This Atlas is not on a personal or devbox database branch.'} ` +
44
+ 'Preview changes database rows, so it refuses any branch other people share.',
45
+ };
46
+ }
47
+ if (!functions.localRuntime) {
48
+ return { ok: false, reason: 'this local Atlas does not run functions locally, so a preview could reach a hosted runtime.' };
49
+ }
50
+ return {
51
+ ok: true,
52
+ target: {
53
+ origin: new URL(url).origin,
54
+ database: {
55
+ branch: database.branch,
56
+ ...(database.host ? { host: database.host } : {}),
57
+ ...(database.endpoint ? { endpoint: database.endpoint } : {}),
58
+ ...(database.name ? { name: database.name } : {}),
59
+ },
60
+ },
61
+ };
62
+ }
@@ -16,14 +16,3 @@
16
16
  * package registry run: an agent sandbox reaches its Atlas origin and nothing else.
17
17
  */
18
18
  export declare function runArtifactCommand(sub: string | undefined, rest: string[]): Promise<number>;
19
- /**
20
- * Strip the seq-studio-only `--pr <number>` and `--env-url <url>` flags from
21
- * argv and return the rest (forwarded to artifact-studio) plus the parsed
22
- * values. These never reach artifact-studio — they're consumed here to resolve
23
- * the preview base URL.
24
- */
25
- export declare function extractPreviewFlags(argv: readonly string[]): {
26
- rest: string[];
27
- prNumber?: number;
28
- envUrl?: string;
29
- };