@sequenceholdings/studio-cli 0.1.27 → 0.1.28

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 (61) hide show
  1. package/README.md +255 -72
  2. package/dist/app/adapters.d.ts +9 -0
  3. package/dist/app/adapters.js +176 -0
  4. package/dist/app/commands.d.ts +2 -2
  5. package/dist/app/commands.js +98 -22
  6. package/dist/app/deploy.d.ts +9 -10
  7. package/dist/app/deploy.js +83 -141
  8. package/dist/app/graph.d.ts +15 -0
  9. package/dist/app/graph.js +36 -0
  10. package/dist/app/manifest-validation.d.ts +16 -0
  11. package/dist/app/manifest-validation.js +99 -0
  12. package/dist/app/manifest.d.ts +27 -9
  13. package/dist/app/manifest.js +23 -107
  14. package/dist/app/paths.d.ts +14 -0
  15. package/dist/app/paths.js +77 -0
  16. package/dist/app/primitive-scaffold.d.ts +18 -0
  17. package/dist/app/primitive-scaffold.js +136 -0
  18. package/dist/app/readme.d.ts +4 -18
  19. package/dist/app/readme.js +105 -233
  20. package/dist/app/run-deployment.d.ts +8 -0
  21. package/dist/app/run-deployment.js +50 -0
  22. package/dist/app/scaffold-files.d.ts +13 -0
  23. package/dist/app/scaffold-files.js +68 -0
  24. package/dist/app/scaffold.d.ts +11 -3
  25. package/dist/app/scaffold.js +77 -245
  26. package/dist/app/workspace-compile.d.ts +18 -0
  27. package/dist/app/workspace-compile.js +143 -0
  28. package/dist/app/workspace-model.d.ts +70 -0
  29. package/dist/app/workspace-model.js +159 -0
  30. package/dist/app/workspace-scaffold.d.ts +27 -0
  31. package/dist/app/workspace-scaffold.js +126 -0
  32. package/dist/app/workspace.d.ts +14 -0
  33. package/dist/app/workspace.js +147 -0
  34. package/dist/atlas-client.js +28 -6
  35. package/dist/auth-cmds/commands.d.ts +1 -1
  36. package/dist/auth-cmds/commands.js +5 -2
  37. package/dist/functions/commands.js +7 -1
  38. package/dist/functions/manifest.d.ts +18 -0
  39. package/dist/functions/manifest.js +29 -4
  40. package/dist/main.js +8 -3
  41. package/dist/pat-hints.js +1 -0
  42. package/dist/pipeline/commands.js +27 -9
  43. package/dist/pipeline/lifecycle.d.ts +2 -0
  44. package/dist/pipeline/lifecycle.js +91 -11
  45. package/dist/process/build.js +59 -43
  46. package/dist/process/codegen.d.ts +3 -2
  47. package/dist/process/codegen.js +143 -27
  48. package/dist/process/commands.d.ts +2 -0
  49. package/dist/process/commands.js +63 -18
  50. package/dist/process/discover.d.ts +6 -3
  51. package/dist/process/discover.js +11 -3
  52. package/dist/process/lint.d.ts +14 -0
  53. package/dist/process/lint.js +143 -5
  54. package/dist/process/plan-diff.d.ts +8 -0
  55. package/dist/process/plan-diff.js +61 -4
  56. package/dist/process/safety-baseline.d.ts +154 -0
  57. package/dist/process/safety-baseline.js +387 -0
  58. package/dist/process/simulate.js +64 -22
  59. package/dist/repos/commands.d.ts +1 -1
  60. package/dist/repos/commands.js +29 -3
  61. package/package.json +6 -5
@@ -1,216 +1,56 @@
1
1
  /**
2
- * Scaffold ORM / function / artifact into an app monorepo and keep
2
+ * Scaffold platform primitives into an app monorepo and keep
3
3
  * sequence.app.yml in sync. Delegates to each primitive's real `init`.
4
4
  */
5
5
  import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
6
6
  import { existsSync } from 'node:fs';
7
- import { dirname, join, relative, resolve } from 'node:path';
8
- import { functionsInitCommand } from '../functions/commands.js';
9
- import { parseArgs } from '../process/commands.js';
10
- import { currentVersion } from '../update-check.js';
11
- import { defaultDeployOrder, extendDeployOrder, loadAppManifest, ormNamespaceFromAppId, titleizeSlug, writeAppManifest, } from './manifest.js';
12
- import { isGitServiceSeedReadme, renderAppReadme } from './readme.js';
7
+ import { join, relative, resolve } from 'node:path';
8
+ import { currentVersion, isNewerVersion } from '../update-check.js';
9
+ import { extendDeployOrder, loadAppManifest, titleizeSlug, writeAppManifest, } from './manifest.js';
10
+ import { inspectScaffoldTarget, mergeGitignore, rollbackAppScaffold } from './scaffold-files.js';
11
+ import { renderAppReadme } from './readme.js';
12
+ import { primitiveIdFor, relativePathFor, scaffoldKind } from './primitive-scaffold.js';
13
+ import { joinAppWorkspace, scaffoldAppWorkspace, scaffoldSharedPackage } from './workspace-scaffold.js';
13
14
  const LOG = '[seq-studio]';
14
15
  const APP_MANIFEST_LABEL = 'sequence.app.yml';
15
- /** Metadata a checkout may have without counting as a docs-only repository. */
16
- const INIT_METADATA_ONLY = new Set(['.git', '.gitattributes', '.DS_Store']);
17
- /**
18
- * Extra names allowed beside a git-service seed README. Presence of any of
19
- * these without that seed marker is treated as a non-empty user directory.
20
- */
21
- const INIT_ALLOWED_EXISTING = new Set([
22
- ...INIT_METADATA_ONLY,
23
- '.gitignore',
24
- 'README.md',
25
- 'LICENSE',
26
- 'LICENSE.md',
27
- ]);
28
- const DEFAULT_GITIGNORE_LINES = [
29
- 'node_modules/',
30
- 'dist/',
31
- '.env',
32
- '.env.*',
33
- '!.env.example',
34
- '.DS_Store',
35
- '*.log',
36
- ];
37
- /** Append missing Sequence ignores; keep existing lines and comments. */
38
- function mergeGitignore(existing) {
39
- const defaults = DEFAULT_GITIGNORE_LINES;
40
- if (existing === null) {
41
- return `${defaults.join('\n')}\n`;
42
- }
43
- const present = new Set(existing
44
- .split(/\r?\n/)
45
- .map((line) => line.trim())
46
- .filter((line) => line.length > 0 && !line.startsWith('#')));
47
- const missing = defaults.filter((line) => !present.has(line));
48
- if (missing.length === 0) {
49
- return existing.endsWith('\n') ? existing : `${existing}\n`;
50
- }
51
- const base = existing.endsWith('\n') ? existing : `${existing}\n`;
52
- return `${base}${missing.join('\n')}\n`;
53
- }
54
16
  export function defaultScaffoldNames(_appId) {
55
17
  return { functionName: 'hello' };
56
18
  }
57
- function primitiveIdFor({ kind, name }) {
58
- switch (kind) {
59
- case 'orm':
60
- return `${name}-orm`;
61
- case 'artifact':
62
- return `${name}-ui`;
63
- case 'function':
64
- return name;
65
- }
66
- }
67
- function relativePathFor({ kind, appId, name, }) {
68
- switch (kind) {
69
- case 'orm':
70
- return join('orm', ormNamespaceFromAppId(appId));
71
- case 'function':
72
- return join('functions', name);
73
- case 'artifact':
74
- return 'artifact';
75
- }
76
- }
77
- function buildPrimitiveEntry({ kind, appId, name, dependsOn, }) {
78
- const path = relativePathFor({ kind, appId, name }).replace(/\\/g, '/');
79
- const id = primitiveIdFor({ kind, name: kind === 'orm' || kind === 'artifact' ? appId : name });
80
- const base = { id, kind, path, depends_on: dependsOn };
81
- switch (kind) {
82
- case 'orm':
83
- return { ...base, namespace: ormNamespaceFromAppId(appId) };
84
- case 'function':
85
- return { ...base, slug: name };
86
- case 'artifact':
87
- return { ...base, project_id: appId };
88
- }
89
- }
90
- async function rewriteArtifactIdentity({ artifactDir, appId, }) {
91
- const title = titleizeSlug(appId);
92
- const manifestPath = join(artifactDir, 'artifact.bundle.yml');
93
- if (existsSync(manifestPath)) {
94
- const body = await readFile(manifestPath, 'utf8');
95
- const next = body
96
- .replace(/(project_id:\s*)\S+/g, `$1${appId}`)
97
- .replace(/^(\s*)title:\s*.*$/m, `$1title: "${title}"`);
98
- if (next !== body)
99
- await writeFile(manifestPath, next, 'utf8');
100
- }
101
- const pkgPath = join(artifactDir, 'package.json');
102
- if (existsSync(pkgPath)) {
103
- try {
104
- const pkg = JSON.parse(await readFile(pkgPath, 'utf8'));
105
- pkg.name = appId;
106
- await writeFile(pkgPath, `${JSON.stringify(pkg, null, 2)}\n`, 'utf8');
107
- }
108
- catch {
109
- // leave non-JSON package.json alone
110
- }
111
- }
112
- }
113
- async function scaffoldOrm({ absPath }) {
114
- const { runOrmCommand } = await import('../orm/delegate.js');
115
- const code = await runOrmCommand('init', [absPath]);
116
- if (code !== 0) {
117
- throw new Error(`orm init failed for ${absPath} (exit ${code}). ` +
118
- '`seq-studio init --with orm` requires `@sequenceholdings/orm` ' +
119
- '(workspace / internal installs today; not yet available via public npm).');
120
- }
121
- }
122
- async function scaffoldArtifact({ absPath, appId, }) {
123
- const { runCli } = await import('@sequenceholdings/artifact-studio/cli');
124
- const code = await runCli(['init', absPath]);
125
- if (code !== 0) {
126
- throw new Error(`artifact init failed for ${absPath} (exit ${code})`);
127
- }
128
- await rewriteArtifactIdentity({ artifactDir: absPath, appId });
129
- }
130
- async function scaffoldFunction({ absPath }) {
131
- const code = await functionsInitCommand(parseArgs([absPath]));
132
- if (code !== 0) {
133
- throw new Error(`functions init failed for ${absPath} (exit ${code})`);
19
+ function assertScaffoldName(name) {
20
+ if (!/^[a-z][a-z0-9-]*$/.test(name)) {
21
+ throw new Error(`invalid scaffold name "${name}" — use kebab-case starting with a letter`);
134
22
  }
135
23
  }
136
- async function scaffoldKind({ kind, appRoot, appId, name, }) {
137
- const relPath = relativePathFor({ kind, appId, name }).replace(/\\/g, '/');
138
- const absPath = join(appRoot, relPath);
139
- const entry = buildPrimitiveEntry({ kind, appId, name, dependsOn: [] });
140
- switch (kind) {
141
- case 'orm':
142
- await mkdir(dirname(absPath), { recursive: true });
143
- await scaffoldOrm({ absPath });
144
- break;
145
- case 'function':
146
- await scaffoldFunction({ absPath });
147
- break;
148
- case 'artifact':
149
- await mkdir(absPath, { recursive: true });
150
- await scaffoldArtifact({ absPath, appId });
151
- break;
152
- }
153
- return entry;
154
- }
155
24
  function applyDefaultDependsOn(primitives) {
156
25
  const orm = primitives.find((entry) => entry.kind === 'orm');
157
26
  if (!orm)
158
27
  return primitives;
159
28
  return primitives.map((entry) => {
160
- if (entry.kind === 'orm' || entry.depends_on.length > 0)
29
+ if (!['function', 'artifact'].includes(entry.kind) || entry.depends_on.length > 0)
161
30
  return entry;
162
31
  return { ...entry, depends_on: [orm.id] };
163
32
  });
164
33
  }
165
- export async function initAppMonorepo({ rootDir, appId, kinds, names = defaultScaffoldNames(appId), description, }) {
34
+ export async function initAppMonorepo({ rootDir, appId, kinds, names = defaultScaffoldNames(appId), description, pipelineType, }) {
166
35
  if (kinds.length === 0) {
167
- throw new Error('select at least one primitive via --with orm,function,artifact (or --orm --function …)');
36
+ throw new Error('select at least one primitive via --with orm,function,agent,process,pipeline,artifact (or --orm --function …)');
168
37
  }
38
+ assertScaffoldName(appId);
39
+ assertScaffoldName(names.functionName);
169
40
  const appRoot = resolve(rootDir);
170
- if (existsSync(join(appRoot, 'sequence.app.yml'))) {
171
- throw new Error(`${join(appRoot, 'sequence.app.yml')} already exists — refusing to re-init`);
172
- }
173
- const { readdir } = await import('node:fs/promises');
174
- const existed = existsSync(appRoot);
175
- const entries = existed
176
- ? await readdir(appRoot).catch((error) => {
177
- if (error.code === 'ENOENT')
178
- return [];
179
- throw error;
180
- })
181
- : [];
182
- const unexpected = entries.filter((name) => !INIT_ALLOWED_EXISTING.has(name));
183
- if (unexpected.length > 0) {
184
- throw new Error(`${appRoot} is not empty — init into a new directory, a git-service clone whose README contains the seq-studio seed marker, or remove existing files first`);
185
- }
186
- const contentful = entries.filter((name) => !INIT_METADATA_ONLY.has(name));
187
- if (contentful.length > 0) {
188
- const readmePath = join(appRoot, 'README.md');
189
- if (!existsSync(readmePath)) {
190
- throw new Error(`${appRoot} is not empty — init into a git-service clone only when README.md contains the seq-studio git-service seed marker`);
191
- }
192
- const existingReadme = await readFile(readmePath, 'utf8');
193
- if (!isGitServiceSeedReadme(existingReadme)) {
194
- throw new Error(`${appRoot} already has a README.md that is not a git-service seed — refusing to overwrite it. Init into a new directory, or keep the platform-generated README from \`seq-studio repos create\`.`);
195
- }
196
- }
197
- const previousReadme = existsSync(join(appRoot, 'README.md'))
198
- ? await readFile(join(appRoot, 'README.md'), 'utf8')
199
- : null;
200
- const previousGitignore = existsSync(join(appRoot, '.gitignore'))
201
- ? await readFile(join(appRoot, '.gitignore'), 'utf8')
202
- : null;
41
+ const snapshot = await inspectScaffoldTarget(appRoot);
203
42
  await mkdir(appRoot, { recursive: true });
204
43
  try {
205
44
  const version = currentVersion();
206
45
  const primitives = [];
207
46
  for (const kind of kinds) {
208
47
  const name = kind === 'function' ? names.functionName : appId;
209
- primitives.push(await scaffoldKind({ kind, appRoot, appId, name }));
48
+ primitives.push(await scaffoldKind({ kind, appRoot, appId, name, pipelineType }));
210
49
  }
211
50
  const withDeps = applyDefaultDependsOn(primitives);
51
+ const shared = await scaffoldSharedPackage({ rootDir: appRoot, appId, name: 'shared' });
212
52
  const manifest = {
213
- schema_version: 1,
53
+ schema_version: 2,
214
54
  app: {
215
55
  id: appId,
216
56
  title: titleizeSlug(appId),
@@ -221,13 +61,14 @@ export async function initAppMonorepo({ rootDir, appId, kinds, names = defaultSc
221
61
  min_cli: version,
222
62
  },
223
63
  primitives: withDeps,
64
+ packages: [shared],
224
65
  deploy: {
225
- order: defaultDeployOrder(withDeps),
226
66
  on_error: 'stop',
227
67
  },
228
68
  };
69
+ await scaffoldAppWorkspace({ rootDir: appRoot, manifest });
229
70
  await writeAppManifest({ rootDir: appRoot, manifest });
230
- await writeFile(join(appRoot, '.gitignore'), mergeGitignore(previousGitignore), 'utf8');
71
+ await writeFile(join(appRoot, '.gitignore'), mergeGitignore(snapshot.previousGitignore), 'utf8');
231
72
  await writeFile(join(appRoot, 'README.md'), renderAppReadme({
232
73
  appId,
233
74
  title: manifest.app.title,
@@ -238,62 +79,27 @@ export async function initAppMonorepo({ rootDir, appId, kinds, names = defaultSc
238
79
  return manifest;
239
80
  }
240
81
  catch (error) {
241
- if (!existed) {
242
- // Directory was newly created — remove the partial scaffold.
243
- await rm(appRoot, { recursive: true, force: true }).catch(() => {
244
- /* best-effort */
245
- });
246
- }
247
- else {
248
- // Reused a git-service clone — only remove what this invocation added.
249
- await rm(join(appRoot, 'sequence.app.yml'), { force: true }).catch(() => {
250
- /* best-effort */
251
- });
252
- for (const kind of kinds) {
253
- const name = kind === 'function' ? names.functionName : appId;
254
- const relPath = relativePathFor({ kind, appId, name }).replace(/\\/g, '/');
255
- const top = relPath.split('/')[0];
256
- if (top) {
257
- await rm(join(appRoot, top), { recursive: true, force: true }).catch(() => {
258
- /* best-effort */
259
- });
260
- }
261
- }
262
- if (previousReadme !== null) {
263
- await writeFile(join(appRoot, 'README.md'), previousReadme, 'utf8').catch(() => {
264
- /* best-effort */
265
- });
266
- }
267
- else {
268
- await rm(join(appRoot, 'README.md'), { force: true }).catch(() => {
269
- /* best-effort */
270
- });
271
- }
272
- if (previousGitignore !== null) {
273
- await writeFile(join(appRoot, '.gitignore'), previousGitignore, 'utf8').catch(() => {
274
- /* best-effort */
275
- });
276
- }
277
- else {
278
- await rm(join(appRoot, '.gitignore'), { force: true }).catch(() => {
279
- /* best-effort */
280
- });
281
- }
282
- }
82
+ await rollbackAppScaffold({
83
+ appRoot,
84
+ snapshot,
85
+ paths: kinds.map((kind) => relativePathFor({
86
+ kind, appId, name: kind === 'function' ? names.functionName : appId,
87
+ }).replace(/\\/g, '/')),
88
+ });
283
89
  throw error;
284
90
  }
285
91
  }
286
- export async function addPrimitiveToApp({ rootDir, kind, name, }) {
92
+ export async function addPrimitiveToApp({ rootDir, kind, name, pipelineType, dependsOn, }) {
287
93
  const appRoot = resolve(rootDir);
288
94
  const manifest = await loadAppManifest(appRoot);
289
95
  const appId = manifest.app.id;
290
- if (kind === 'orm') {
291
- throw new Error('adding a second orm namespace is not supported via `seq-studio add` yet — edit sequence.app.yml and scaffold with `seq-studio orm init` manually');
292
- }
293
- if (kind === 'artifact' && manifest.primitives.some((entry) => entry.kind === 'artifact')) {
294
- throw new Error('this app already has an artifact primitive — remove it from sequence.app.yml before re-adding');
96
+ assertScaffoldName(name);
97
+ for (const dependency of dependsOn ?? []) {
98
+ if (!manifest.primitives.some((entry) => entry.id === dependency)) {
99
+ throw new Error(`--depends-on references unknown primitive id "${dependency}"`);
100
+ }
295
101
  }
296
- const entryId = primitiveIdFor({ kind, name: kind === 'artifact' ? appId : name });
102
+ const entryId = primitiveIdFor({ kind, name });
297
103
  if (manifest.primitives.some((entry) => entry.id === entryId)) {
298
104
  throw new Error(`primitive id "${entryId}" already exists in sequence.app.yml`);
299
105
  }
@@ -306,30 +112,48 @@ export async function addPrimitiveToApp({ rootDir, kind, name, }) {
306
112
  if (existsSync(absPath)) {
307
113
  throw new Error(`${relPath} already exists on disk — remove it or choose a different name before \`seq-studio add\``);
308
114
  }
115
+ const workspacePath = join(appRoot, 'pnpm-workspace.yaml');
116
+ const previousWorkspace = existsSync(workspacePath) ? await readFile(workspacePath, 'utf8') : null;
309
117
  try {
310
- let entry = await scaffoldKind({ kind, appRoot, appId, name });
118
+ let entry = await scaffoldKind({ kind, appRoot, appId, name, pipelineType });
311
119
  const orm = manifest.primitives.find((item) => item.kind === 'orm');
312
- if (orm && entry.depends_on.length === 0) {
120
+ if (dependsOn !== undefined) {
121
+ entry = { ...entry, depends_on: dependsOn };
122
+ }
123
+ else if (orm && ['function', 'artifact'].includes(kind)) {
313
124
  entry = { ...entry, depends_on: [orm.id] };
314
125
  }
315
126
  const primitives = [...manifest.primitives, entry];
127
+ const upgrade = manifest.schema_version === 1 && ['agent', 'process', 'pipeline'].includes(kind);
128
+ const version = currentVersion();
316
129
  const next = {
317
130
  ...manifest,
131
+ ...(upgrade ? {
132
+ schema_version: 2,
133
+ studio: {
134
+ ...manifest.studio,
135
+ min_cli: isNewerVersion(version, manifest.studio.min_cli) ? version : manifest.studio.min_cli,
136
+ },
137
+ } : {}),
318
138
  primitives,
319
139
  deploy: {
320
140
  ...manifest.deploy,
321
- order: extendDeployOrder({
322
- existingOrder: manifest.deploy.order,
323
- primitives,
324
- newId: entry.id,
325
- }),
141
+ ...(manifest.schema_version === 1 || manifest.deploy.order !== undefined ? { order: extendDeployOrder({
142
+ existingOrder: manifest.deploy.order,
143
+ primitives,
144
+ newId: entry.id,
145
+ }) } : {}),
326
146
  on_error: manifest.deploy.on_error,
327
147
  },
328
148
  };
149
+ if (!upgrade)
150
+ await joinAppWorkspace({ rootDir: appRoot, manifest: next, entries: [entry] });
329
151
  await writeAppManifest({ rootDir: appRoot, manifest: next });
330
152
  return { manifest: next, entry };
331
153
  }
332
154
  catch (error) {
155
+ if (previousWorkspace !== null)
156
+ await writeFile(workspacePath, previousWorkspace, 'utf8');
333
157
  // Safe: absPath did not exist before this invocation.
334
158
  await rm(absPath, { recursive: true, force: true }).catch(() => {
335
159
  /* best-effort */
@@ -337,6 +161,13 @@ export async function addPrimitiveToApp({ rootDir, kind, name, }) {
337
161
  throw error;
338
162
  }
339
163
  }
164
+ export function printOrmPreparation({ primitives }) {
165
+ for (const entry of primitives.filter((item) => item.kind === 'orm')) {
166
+ console.log(` seq-studio orm generate ${entry.path}`);
167
+ console.log(` seq-studio orm diff ${entry.path}`);
168
+ console.log(` # review and commit ${entry.path}/migrations/ before deploying`);
169
+ }
170
+ }
340
171
  export function printInitNextSteps({ appRoot, manifest, }) {
341
172
  const rel = relative(process.cwd(), appRoot);
342
173
  const display = !rel || rel.startsWith('..') ? appRoot : rel;
@@ -348,19 +179,20 @@ export function printInitNextSteps({ appRoot, manifest, }) {
348
179
  console.log('');
349
180
  console.log('Next:');
350
181
  console.log(` cd ${display}`);
351
- for (const entry of manifest.primitives) {
352
- console.log(` (cd ${entry.path} && pnpm install)`);
353
- }
182
+ console.log(' pnpm install');
183
+ printOrmPreparation({ primitives: manifest.primitives });
354
184
  console.log(' seq-studio login');
355
185
  console.log(' seq-studio deploy -e local --yes');
356
186
  console.log(' # or targeted:');
357
187
  const fn = manifest.primitives.find((entry) => entry.kind === 'function');
358
188
  if (fn) {
359
- console.log(` seq-studio functions deploy --dir ${fn.path} -e local --yes`);
189
+ console.log(` seq-studio deploy --only ${fn.id} -e local --yes`);
360
190
  }
361
- if (manifest.primitives.some((entry) => entry.kind === 'artifact')) {
362
- console.log(' seq-studio artifact deploy artifact -e local');
191
+ const artifact = manifest.primitives.find((entry) => entry.kind === 'artifact');
192
+ if (artifact) {
193
+ console.log(` seq-studio deploy --only ${artifact.id} -e local --yes`);
363
194
  }
364
- console.log(' # add another function later:');
195
+ console.log(' # add another primitive later:');
365
196
  console.log(' seq-studio add function list-types');
197
+ console.log(' seq-studio add package contracts');
366
198
  }
@@ -0,0 +1,18 @@
1
+ import { type WorkspacePackage, type WorkspacePackageJson } from './workspace-model.js';
2
+ interface CompileOptions {
3
+ sourceDir: string;
4
+ stageDir: string;
5
+ json: WorkspacePackageJson;
6
+ packages: ReadonlyMap<string, WorkspacePackage>;
7
+ closure: readonly WorkspacePackage[];
8
+ }
9
+ export declare function compileWorkspaceFunction(options: CompileOptions): Promise<void>;
10
+ /**
11
+ * Rewrite only workspace imports in the artifact's own modules, then compile
12
+ * all shared entrypoints together. Shared chunks retain module singleton state;
13
+ * the existing Vite pipeline still owns UI/CSS/assets and platform peer aliases.
14
+ */
15
+ export declare function compileWorkspaceArtifact(options: CompileOptions & {
16
+ sourceFiles: readonly string[];
17
+ }): Promise<void>;
18
+ export {};
@@ -0,0 +1,143 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync } from 'node:fs';
3
+ import { mkdir, readFile, realpath, rm, writeFile } from 'node:fs/promises';
4
+ import { basename, dirname, extname, join, relative, resolve, sep } from 'node:path';
5
+ import { build, transform } from 'esbuild';
6
+ import { z } from 'zod';
7
+ import { containedPath, isWithin, resolveWorkspaceImport } from './workspace-model.js';
8
+ const slash = (path) => path.split(sep).join('/');
9
+ const relativeImport = ({ from, to }) => {
10
+ const path = slash(relative(dirname(from), to));
11
+ return path.startsWith('.') ? path : `./${path}`;
12
+ };
13
+ function workspaceCompilerPlugin({ sourceDir, packages, closure, browser, runtimeEntry, runtimeMain }) {
14
+ const allowed = [...(browser ? [] : [sourceDir]), ...closure.map((entry) => entry.dir)];
15
+ return {
16
+ name: 'sequence-app-workspace-source',
17
+ setup(builder) {
18
+ builder.onResolve({ filter: /^[^./]|^@/ }, async (args) => {
19
+ const path = await resolveWorkspaceImport({ specifier: args.path, packages, browser, requireImport: args.kind === 'require-call' || args.kind === 'require-resolve' });
20
+ if (path)
21
+ return { path };
22
+ return { path: args.path, external: true };
23
+ });
24
+ builder.onLoad({ filter: /./ }, async (args) => {
25
+ const path = await realpath(args.path);
26
+ if (/^\.env(?:\..*)?$/.test(basename(path)))
27
+ throw new Error(`Dotenv files cannot enter compiled app bundles: ${args.path}`);
28
+ if (!allowed.some((root) => isWithin({ root, path })) || path.split(sep).includes('node_modules')) {
29
+ throw new Error(`Workspace import is outside declared app sources: ${args.path}`);
30
+ }
31
+ if (!/\.(?:[cm]?[jt]sx?|json)$/.test(path)) {
32
+ throw new Error(`Shared workspace code imports unsupported asset ${args.path}; keep browser assets in the artifact source directory`);
33
+ }
34
+ if (!browser && !path.endsWith('.json')) {
35
+ const preservesRootLocation = path === runtimeEntry && dirname(path) === sourceDir && !(runtimeMain ?? '').includes('/');
36
+ const sentinel = '__sequence_location_dependent_runtime__';
37
+ const defines = { 'require.resolve': sentinel, 'import.meta': sentinel, __filename: sentinel };
38
+ if (!preservesRootLocation)
39
+ defines.__dirname = sentinel;
40
+ const probe = await transform(await readFile(path, 'utf8'), {
41
+ loader: /\.[cm]?tsx?$/.test(path) ? extname(path).includes('x') ? 'tsx' : 'ts' : 'js',
42
+ define: defines, logLevel: 'silent',
43
+ });
44
+ if (probe.code.includes(sentinel))
45
+ throw new Error(`Function source ${path} uses module-relative runtime locations (import.meta, __dirname, __filename, or require.resolve) that cannot be preserved by workspace bundling. Move data into explicit imports or keep this function self-contained without workspace dependencies.`);
46
+ }
47
+ return undefined;
48
+ });
49
+ },
50
+ };
51
+ }
52
+ async function functionSource({ sourceDir, json }) {
53
+ if (json.seqStudio?.source)
54
+ return containedPath({ root: sourceDir, path: json.seqStudio.source });
55
+ const main = json.main ?? 'index.js';
56
+ if (json.scripts?.build !== 'tsc') {
57
+ if (existsSync(resolve(sourceDir, main)))
58
+ return containedPath({ root: sourceDir, path: main });
59
+ throw new Error(`Function ${json.name ?? sourceDir}: ${main} does not exist. Run its build first or set package.json seqStudio.source to the runtime source entrypoint`);
60
+ }
61
+ const config = z.object({ compilerOptions: z.object({ outDir: z.string().optional(), rootDir: z.string().optional() }).optional() }).parse(JSON.parse(await readFile(join(sourceDir, 'tsconfig.json'), 'utf8')));
62
+ const outDir = config.compilerOptions?.outDir;
63
+ const rootDir = config.compilerOptions?.rootDir;
64
+ if (typeof outDir !== 'string' || typeof rootDir !== 'string' || !main.startsWith(`${outDir}/`)) {
65
+ throw new Error(`Function ${json.name ?? sourceDir}: set package.json seqStudio.source; its TypeScript source entrypoint cannot be inferred from main/rootDir/outDir`);
66
+ }
67
+ const source = join(rootDir, main.slice(outDir.length + 1)).replace(/\.[cm]?js$/, '.ts');
68
+ return containedPath({ root: sourceDir, path: source });
69
+ }
70
+ export async function compileWorkspaceFunction(options) {
71
+ const source = await functionSource(options);
72
+ const entry = options.json.type === 'module' ? '.sequence-runtime.mjs' : '.sequence-runtime.cjs';
73
+ const result = await build({
74
+ entryPoints: [source], outfile: join(options.stageDir, entry), write: false,
75
+ bundle: true, platform: 'node', format: options.json.type === 'module' ? 'esm' : 'cjs', target: 'node20', packages: 'external',
76
+ absWorkingDir: options.sourceDir, logOverride: { 'empty-import-meta': 'error' },
77
+ sourcemap: false, logLevel: 'silent',
78
+ plugins: [workspaceCompilerPlugin({ ...options, browser: false, runtimeEntry: source, runtimeMain: options.json.main })],
79
+ });
80
+ for (const output of result.outputFiles)
81
+ await writeFile(output.path, output.contents);
82
+ options.json.main = entry;
83
+ // The function worker detects TypeScript through root index.ts + tsconfig;
84
+ // this staged upload already contains the completed JavaScript runtime.
85
+ await rm(join(options.stageDir, 'tsconfig.json'), { force: true });
86
+ // The staged entry is the completed runtime output. Custom build outputs
87
+ // must exist before this step, or authors explicitly select seqStudio.source.
88
+ if (options.json.scripts) {
89
+ delete options.json.scripts.build;
90
+ delete options.json.scripts['gcp-build'];
91
+ }
92
+ }
93
+ /**
94
+ * Rewrite only workspace imports in the artifact's own modules, then compile
95
+ * all shared entrypoints together. Shared chunks retain module singleton state;
96
+ * the existing Vite pipeline still owns UI/CSS/assets and platform peer aliases.
97
+ */
98
+ export async function compileWorkspaceArtifact(options) {
99
+ const entries = new Map();
100
+ const outputRoot = join(options.stageDir, '.sequence-packages');
101
+ const packageImportPlugin = {
102
+ name: 'sequence-artifact-workspace-imports',
103
+ setup(builder) {
104
+ builder.onResolve({ filter: /.*/ }, async (args) => {
105
+ if (args.kind === 'entry-point')
106
+ return undefined;
107
+ const path = await resolveWorkspaceImport({ specifier: args.path, packages: options.packages, browser: true, requireImport: args.kind === 'require-call' || args.kind === 'require-resolve' });
108
+ if (!path)
109
+ return { path: args.path, external: true };
110
+ const name = createHash('sha256').update(slash(relative(options.sourceDir, path))).digest('hex').slice(0, 20);
111
+ entries.set(name, path);
112
+ return { path: relativeImport({ from: builder.initialOptions.outfile, to: join(outputRoot, `${name}.js`) }), external: true };
113
+ });
114
+ },
115
+ };
116
+ for (const file of options.sourceFiles) {
117
+ if (!/\.[cm]?[jt]sx?$/.test(file) || /\.d\.[cm]?ts$/.test(file))
118
+ continue;
119
+ const path = join(options.stageDir, file);
120
+ const contents = await readFile(path, 'utf8');
121
+ if (!options.closure.some((pkg) => contents.includes(pkg.name)))
122
+ continue;
123
+ const result = await build({
124
+ stdin: { contents, sourcefile: path, resolveDir: dirname(path), loader: extname(file).includes('x') ? 'tsx' : /\.[cm]?ts$/.test(file) ? 'ts' : 'js' },
125
+ outfile: path, write: false, bundle: true, format: /\.(?:cjs|cts)$/.test(file) ? 'cjs' : 'esm', platform: 'browser',
126
+ absWorkingDir: options.stageDir, logOverride: { 'empty-import-meta': 'error' },
127
+ jsx: 'preserve', sourcemap: false, logLevel: 'silent', plugins: [packageImportPlugin],
128
+ });
129
+ await writeFile(path, result.outputFiles[0].contents);
130
+ }
131
+ if (entries.size === 0)
132
+ return;
133
+ const result = await build({
134
+ entryPoints: Object.fromEntries(entries), outdir: outputRoot, entryNames: '[name]', chunkNames: 'chunks/[name]-[hash]',
135
+ write: false, bundle: true, splitting: true, format: 'esm', platform: 'browser',
136
+ packages: 'external', jsx: 'automatic', absWorkingDir: options.sourceDir, sourcemap: false, logLevel: 'silent',
137
+ plugins: [workspaceCompilerPlugin({ ...options, browser: true })],
138
+ });
139
+ for (const output of result.outputFiles) {
140
+ await mkdir(dirname(output.path), { recursive: true });
141
+ await writeFile(output.path, output.contents);
142
+ }
143
+ }
@@ -0,0 +1,70 @@
1
+ import { z } from 'zod';
2
+ export declare const packageJsonSchema: z.ZodObject<{
3
+ name: z.ZodOptional<z.ZodString>;
4
+ main: z.ZodOptional<z.ZodString>;
5
+ module: z.ZodOptional<z.ZodString>;
6
+ type: z.ZodOptional<z.ZodString>;
7
+ exports: z.ZodOptional<z.ZodUnknown>;
8
+ dependencies: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
9
+ optionalDependencies: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
10
+ devDependencies: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
11
+ peerDependencies: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
12
+ scripts: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
13
+ pnpm: z.ZodOptional<z.ZodObject<{
14
+ overrides: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
15
+ }, z.core.$loose>>;
16
+ seqStudio: z.ZodOptional<z.ZodObject<{
17
+ source: z.ZodOptional<z.ZodString>;
18
+ }, z.core.$loose>>;
19
+ }, z.core.$loose>;
20
+ export type WorkspacePackageJson = z.infer<typeof packageJsonSchema>;
21
+ export interface WorkspacePackage {
22
+ name: string;
23
+ path: string;
24
+ dir: string;
25
+ json: WorkspacePackageJson;
26
+ }
27
+ export interface WorkspaceManifest {
28
+ packages?: readonly {
29
+ name: string;
30
+ path: string;
31
+ }[];
32
+ }
33
+ export declare const DEPENDENCY_SECTIONS: readonly ["dependencies", "optionalDependencies", "devDependencies", "peerDependencies"];
34
+ export declare const RUNTIME_SECTIONS: readonly ["dependencies", "optionalDependencies", "peerDependencies"];
35
+ export declare function readWorkspacePackage({ dir }: {
36
+ dir: string;
37
+ }): Promise<WorkspacePackageJson>;
38
+ export declare function isWithin({ root, path }: {
39
+ root: string;
40
+ path: string;
41
+ }): boolean;
42
+ export declare function containedPath({ root, path }: {
43
+ root: string;
44
+ path: string;
45
+ }): Promise<string>;
46
+ export declare function loadWorkspacePackages({ rootDir, manifest }: {
47
+ rootDir: string;
48
+ manifest: WorkspaceManifest;
49
+ }): Promise<Map<string, WorkspacePackage>>;
50
+ export declare function workspaceDependency({ name, spec, packages }: {
51
+ name: string;
52
+ spec: string;
53
+ packages: ReadonlyMap<string, WorkspacePackage>;
54
+ }): WorkspacePackage | undefined;
55
+ export declare function packageClosure({ json, packages }: {
56
+ json: WorkspacePackageJson;
57
+ packages: ReadonlyMap<string, WorkspacePackage>;
58
+ }): WorkspacePackage[];
59
+ /** The upload is registry-only after workspace code has been compiled into it. */
60
+ export declare function deploymentPackageJson({ json, closure, platformPeers }: {
61
+ json: WorkspacePackageJson;
62
+ closure: readonly WorkspacePackage[];
63
+ platformPeers?: ReadonlySet<string>;
64
+ }): WorkspacePackageJson;
65
+ export declare function resolveWorkspaceImport({ specifier, packages, browser, requireImport }: {
66
+ specifier: string;
67
+ packages: ReadonlyMap<string, WorkspacePackage>;
68
+ browser: boolean;
69
+ requireImport?: boolean;
70
+ }): Promise<string | undefined>;