@tailor-platform/sdk 1.1.3 → 1.2.0

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.
@@ -7,7 +7,10 @@ import path from "node:path";
7
7
  import { loadEnvFile } from "node:process";
8
8
  import { z } from "zod";
9
9
  import chalk from "chalk";
10
+ import util, { formatWithOptions } from "node:util";
10
11
  import { createConsola } from "consola";
12
+ import { formatDistanceToNowStrict } from "date-fns";
13
+ import { getBorderCharacters, table } from "table";
11
14
  import { OAuth2Client } from "@badgateway/oauth2-client";
12
15
  import { MethodOptions_IdempotencyLevel, ValueSchema, file_google_protobuf_descriptor, file_google_protobuf_duration, file_google_protobuf_field_mask, file_google_protobuf_struct, file_google_protobuf_timestamp, timestampDate } from "@bufbuild/protobuf/wkt";
13
16
  import { Code, ConnectError, createClient } from "@connectrpc/connect";
@@ -24,7 +27,6 @@ import ml from "multiline-ts";
24
27
  import { xdgConfig } from "xdg-basedir";
25
28
  import { pathToFileURL } from "node:url";
26
29
  import { glob } from "node:fs/promises";
27
- import util from "node:util";
28
30
  import assert from "node:assert";
29
31
  import * as inflection from "inflection";
30
32
  import * as rolldown from "rolldown";
@@ -33,8 +35,6 @@ import { create, fromJson } from "@bufbuild/protobuf";
33
35
  import { spawn } from "node:child_process";
34
36
  import chokidar from "chokidar";
35
37
  import * as madgeModule from "madge";
36
- import { formatDistanceToNowStrict } from "date-fns";
37
- import { getBorderCharacters, table } from "table";
38
38
  import ora from "ora";
39
39
 
40
40
  //#region src/cli/utils/errors.ts
@@ -250,19 +250,64 @@ const symbols = {
250
250
  bullet: chalk.gray("•"),
251
251
  arrow: chalk.gray("→")
252
252
  };
253
- const defaultLogger = createConsola({ formatOptions: { date: false } });
254
- const streamLogger = createConsola({ formatOptions: { date: true } });
255
- const plainLogger = createConsola({ formatOptions: {
256
- date: false,
257
- compact: true
258
- } });
259
- /**
260
- * Logger object for CLI output
261
- */
253
+ let _jsonMode = false;
254
+ const TYPE_ICONS = {
255
+ info: "ℹ",
256
+ success: "✔",
257
+ warn: "⚠",
258
+ error: "✖",
259
+ debug: "⚙",
260
+ trace: "→",
261
+ log: ""
262
+ };
263
+ var IconReporter = class {
264
+ log(logObj, ctx) {
265
+ const stdout = ctx.options.stdout || process.stdout;
266
+ const stderr = ctx.options.stderr || process.stderr;
267
+ const formatOptions = ctx.options.formatOptions;
268
+ const message = formatWithOptions({
269
+ breakLength: stdout.columns || 80,
270
+ compact: formatOptions.compact
271
+ }, ...logObj.args);
272
+ const icon = TYPE_ICONS[logObj.type] || "";
273
+ const prefix = icon ? `${icon} ` : "";
274
+ const timestamp = formatOptions.date && logObj.date ? `${logObj.date.toLocaleTimeString()} ` : "";
275
+ stderr.write(`${timestamp}${prefix}${message}\n`);
276
+ }
277
+ };
278
+ var PlainReporter = class {
279
+ log(logObj, ctx) {
280
+ const stderr = ctx.options.stderr || process.stderr;
281
+ const message = formatWithOptions({
282
+ breakLength: 100,
283
+ compact: ctx.options.formatOptions.compact
284
+ }, ...logObj.args);
285
+ stderr.write(`${message}\n`);
286
+ }
287
+ };
288
+ const defaultLogger = createConsola({
289
+ reporters: [new IconReporter()],
290
+ formatOptions: { date: false }
291
+ });
292
+ const streamLogger = createConsola({
293
+ reporters: [new IconReporter()],
294
+ formatOptions: { date: true }
295
+ });
296
+ const plainLogger = createConsola({
297
+ reporters: [new PlainReporter()],
298
+ formatOptions: {
299
+ date: false,
300
+ compact: true
301
+ }
302
+ });
262
303
  const logger = {
263
- jsonMode: false,
304
+ get jsonMode() {
305
+ return _jsonMode;
306
+ },
307
+ set jsonMode(value) {
308
+ _jsonMode = value;
309
+ },
264
310
  info(message, opts) {
265
- if (this.jsonMode) return;
266
311
  switch (opts?.mode ?? "default") {
267
312
  case "stream":
268
313
  streamLogger.info(message);
@@ -274,7 +319,6 @@ const logger = {
274
319
  }
275
320
  },
276
321
  success(message, opts) {
277
- if (this.jsonMode) return;
278
322
  switch (opts?.mode ?? "default") {
279
323
  case "stream":
280
324
  streamLogger.success(message);
@@ -286,7 +330,6 @@ const logger = {
286
330
  }
287
331
  },
288
332
  warn(message, opts) {
289
- if (this.jsonMode) return;
290
333
  switch (opts?.mode ?? "default") {
291
334
  case "stream":
292
335
  streamLogger.warn(message);
@@ -309,21 +352,45 @@ const logger = {
309
352
  }
310
353
  },
311
354
  log(message) {
312
- if (this.jsonMode) return;
313
355
  plainLogger.log(message);
314
356
  },
315
357
  newline() {
316
- if (this.jsonMode) return;
317
358
  plainLogger.log("");
318
359
  },
319
360
  debug(message) {
320
- if (this.jsonMode) return;
321
361
  plainLogger.log(styles.dim(message));
322
362
  },
323
- data(dataValue, formatFn) {
324
- if (this.jsonMode) plainLogger.log(JSON.stringify(dataValue, null, 2));
325
- else if (formatFn) formatFn(dataValue);
326
- else plainLogger.log(String(dataValue));
363
+ out(data$1) {
364
+ if (typeof data$1 === "string") {
365
+ process.stdout.write(data$1.endsWith("\n") ? data$1 : data$1 + "\n");
366
+ return;
367
+ }
368
+ if (this.jsonMode) {
369
+ console.log(JSON.stringify(data$1));
370
+ return;
371
+ }
372
+ if (!Array.isArray(data$1)) {
373
+ const t$2 = table(Object.entries(data$1), {
374
+ singleLine: true,
375
+ border: getBorderCharacters("norc")
376
+ });
377
+ process.stdout.write(t$2);
378
+ return;
379
+ }
380
+ if (data$1.length === 0) return;
381
+ const headers = Array.from(new Set(data$1.flatMap((item) => Object.keys(item))));
382
+ const t$1 = table([headers, ...data$1.map((item) => headers.map((header) => {
383
+ const value = item[header];
384
+ if (value === null || value === void 0) return "";
385
+ if ((header === "createdAt" || header === "updatedAt") && typeof value === "string") return formatDistanceToNowStrict(new Date(value), { addSuffix: true });
386
+ return String(value);
387
+ }))], {
388
+ border: getBorderCharacters("norc"),
389
+ drawHorizontalLine: (lineIndex, rowCount) => {
390
+ return lineIndex === 0 || lineIndex === 1 || lineIndex === rowCount;
391
+ }
392
+ });
393
+ process.stdout.write(t$1);
327
394
  },
328
395
  prompt(message, options) {
329
396
  if (T) throw new CIPromptError();
@@ -100795,11 +100862,11 @@ function trnPrefix(workspaceId) {
100795
100862
  return `trn:v1:workspace:${workspaceId}`;
100796
100863
  }
100797
100864
  const sdkNameLabelKey = "sdk-name";
100798
- async function buildMetaRequest(trn$8, appName) {
100865
+ async function buildMetaRequest(trn$7, appName) {
100799
100866
  const packageJson$1 = await readPackageJson();
100800
100867
  const sdkVersion = packageJson$1.version ? `v${packageJson$1.version.replace(/\./g, "-")}` : "unknown";
100801
100868
  return {
100802
- trn: trn$8,
100869
+ trn: trn$7,
100803
100870
  labels: {
100804
100871
  [sdkNameLabelKey]: appName,
100805
100872
  "sdk-version": sdkVersion
@@ -100850,7 +100917,7 @@ async function applyApplication(client, changeSet, phase = "create-update") {
100850
100917
  await client.deleteApplication(del.request);
100851
100918
  }));
100852
100919
  }
100853
- function trn$7(workspaceId, name$1) {
100920
+ function trn$6(workspaceId, name$1) {
100854
100921
  return `trn:v1:workspace:${workspaceId}:application:${name$1}`;
100855
100922
  }
100856
100923
  async function planApplication({ client, workspaceId, application, forRemoval }) {
@@ -100901,7 +100968,7 @@ async function planApplication({ client, workspaceId, application, forRemoval })
100901
100968
  });
100902
100969
  if (idpConfigs.length > 0) authIdpConfigName = idpConfigs[0].name;
100903
100970
  }
100904
- const metaRequest = await buildMetaRequest(trn$7(workspaceId, application.name), application.name);
100971
+ const metaRequest = await buildMetaRequest(trn$6(workspaceId, application.name), application.name);
100905
100972
  if (existingApplications.some((app) => app.name === application.name)) changeSet.updates.push({
100906
100973
  name: application.name,
100907
100974
  request: {
@@ -101037,7 +101104,7 @@ async function planIdP({ client, workspaceId, application, forRemoval }) {
101037
101104
  resourceOwners
101038
101105
  };
101039
101106
  }
101040
- function trn$6(workspaceId, name$1) {
101107
+ function trn$5(workspaceId, name$1) {
101041
101108
  return `trn:v1:workspace:${workspaceId}:idp:${name$1}`;
101042
101109
  }
101043
101110
  async function planServices$3(client, workspaceId, appName, idps) {
@@ -101060,7 +101127,7 @@ async function planServices$3(client, workspaceId, appName, idps) {
101060
101127
  const existingServices = {};
101061
101128
  await Promise.all(withoutLabel.map(async (resource) => {
101062
101129
  if (!resource.namespace?.name) return;
101063
- const { metadata } = await client.getMetadata({ trn: trn$6(workspaceId, resource.namespace.name) });
101130
+ const { metadata } = await client.getMetadata({ trn: trn$5(workspaceId, resource.namespace.name) });
101064
101131
  existingServices[resource.namespace.name] = {
101065
101132
  resource,
101066
101133
  label: metadata?.labels[sdkNameLabelKey]
@@ -101069,7 +101136,7 @@ async function planServices$3(client, workspaceId, appName, idps) {
101069
101136
  for (const idp of idps) {
101070
101137
  const namespaceName = idp.name;
101071
101138
  const existing = existingServices[namespaceName];
101072
- const metaRequest = await buildMetaRequest(trn$6(workspaceId, namespaceName), appName);
101139
+ const metaRequest = await buildMetaRequest(trn$5(workspaceId, namespaceName), appName);
101073
101140
  let authorization;
101074
101141
  switch (idp.authorization) {
101075
101142
  case "insecure":
@@ -101284,7 +101351,7 @@ async function planAuth({ client, workspaceId, application, forRemoval }) {
101284
101351
  resourceOwners
101285
101352
  };
101286
101353
  }
101287
- function trn$5(workspaceId, name$1) {
101354
+ function trn$4(workspaceId, name$1) {
101288
101355
  return `trn:v1:workspace:${workspaceId}:auth:${name$1}`;
101289
101356
  }
101290
101357
  async function planServices$2(client, workspaceId, appName, auths) {
@@ -101307,7 +101374,7 @@ async function planServices$2(client, workspaceId, appName, auths) {
101307
101374
  const existingServices = {};
101308
101375
  await Promise.all(withoutLabel.map(async (resource) => {
101309
101376
  if (!resource.namespace?.name) return;
101310
- const { metadata } = await client.getMetadata({ trn: trn$5(workspaceId, resource.namespace.name) });
101377
+ const { metadata } = await client.getMetadata({ trn: trn$4(workspaceId, resource.namespace.name) });
101311
101378
  existingServices[resource.namespace.name] = {
101312
101379
  resource,
101313
101380
  label: metadata?.labels[sdkNameLabelKey]
@@ -101316,7 +101383,7 @@ async function planServices$2(client, workspaceId, appName, auths) {
101316
101383
  for (const auth of auths) {
101317
101384
  const { parsedConfig: config } = auth;
101318
101385
  const existing = existingServices[config.name];
101319
- const metaRequest = await buildMetaRequest(trn$5(workspaceId, config.name), appName);
101386
+ const metaRequest = await buildMetaRequest(trn$4(workspaceId, config.name), appName);
101320
101387
  if (existing) {
101321
101388
  if (!existing.label) unmanaged.push({
101322
101389
  resourceType: "Auth service",
@@ -102126,7 +102193,7 @@ async function applyExecutor(client, result, phase = "create-update") {
102126
102193
  })]);
102127
102194
  else if (phase === "delete") await Promise.all(changeSet.deletes.map((del) => client.deleteExecutorExecutor(del.request)));
102128
102195
  }
102129
- function trn$4(workspaceId, name$1) {
102196
+ function trn$3(workspaceId, name$1) {
102130
102197
  return `trn:v1:workspace:${workspaceId}:executor:${name$1}`;
102131
102198
  }
102132
102199
  async function planExecutor({ client, workspaceId, application, forRemoval }) {
@@ -102148,7 +102215,7 @@ async function planExecutor({ client, workspaceId, application, forRemoval }) {
102148
102215
  });
102149
102216
  const existingExecutors = {};
102150
102217
  await Promise.all(withoutLabel.map(async (resource) => {
102151
- const { metadata } = await client.getMetadata({ trn: trn$4(workspaceId, resource.name) });
102218
+ const { metadata } = await client.getMetadata({ trn: trn$3(workspaceId, resource.name) });
102152
102219
  existingExecutors[resource.name] = {
102153
102220
  resource,
102154
102221
  label: metadata?.labels[sdkNameLabelKey]
@@ -102157,7 +102224,7 @@ async function planExecutor({ client, workspaceId, application, forRemoval }) {
102157
102224
  const executors = forRemoval ? {} : await application.executorService?.loadExecutors() ?? {};
102158
102225
  for (const executor of Object.values(executors)) {
102159
102226
  const existing = existingExecutors[executor.name];
102160
- const metaRequest = await buildMetaRequest(trn$4(workspaceId, executor.name), application.name);
102227
+ const metaRequest = await buildMetaRequest(trn$3(workspaceId, executor.name), application.name);
102161
102228
  if (existing) {
102162
102229
  if (!existing.label) unmanaged.push({
102163
102230
  resourceType: "Executor",
@@ -102205,10 +102272,20 @@ async function planExecutor({ client, workspaceId, application, forRemoval }) {
102205
102272
  resourceOwners
102206
102273
  };
102207
102274
  }
102275
+ /**
102276
+ * Build args expression for resolverExecuted trigger.
102277
+ * Transforms server's succeeded/failed fields to success/result/error fields.
102278
+ */
102279
+ function buildResolverExecutedArgsExpr(additionalFields) {
102280
+ const baseFields = `...args, appNamespace: args.namespaceName, success: !!args.succeeded, result: args.succeeded?.result.resolver, error: args.failed?.error`;
102281
+ return additionalFields ? `({ ${baseFields}, ${additionalFields} })` : `({ ${baseFields} })`;
102282
+ }
102208
102283
  function protoExecutor(appName, executor, env) {
102209
102284
  const trigger = executor.trigger;
102210
102285
  let triggerType;
102211
102286
  let triggerConfig;
102287
+ const envField = `env: ${JSON.stringify(env)}`;
102288
+ const baseArgsExpr = `({ ...args, appNamespace: args.namespaceName, ${envField} })`;
102212
102289
  const eventType = {
102213
102290
  recordCreated: "tailordb.type_record.created",
102214
102291
  recordUpdated: "tailordb.type_record.updated",
@@ -102234,7 +102311,7 @@ function protoExecutor(appName, executor, env) {
102234
102311
  case: "event",
102235
102312
  value: {
102236
102313
  eventType: eventType[trigger.kind],
102237
- condition: { expr: [`args.typeName === "${trigger.typeName}"`, ...trigger.condition ? [`(${stringifyFunction(trigger.condition)})({ ...args, appNamespace: args.namespaceName })`] : []].join(" && ") }
102314
+ condition: { expr: [`args.typeName === "${trigger.typeName}"`, ...trigger.condition ? [`(${stringifyFunction(trigger.condition)})(${baseArgsExpr})`] : []].join(" && ") }
102238
102315
  }
102239
102316
  } };
102240
102317
  break;
@@ -102244,7 +102321,7 @@ function protoExecutor(appName, executor, env) {
102244
102321
  case: "event",
102245
102322
  value: {
102246
102323
  eventType: eventType[trigger.kind],
102247
- condition: { expr: [`args.resolverName === "${trigger.resolverName}"`, ...trigger.condition ? [`(${stringifyFunction(trigger.condition)})({ ...args, appNamespace: args.namespaceName, result: args.succeeded?.result, error: args.failed?.error })`] : []].join(" && ") }
102324
+ condition: { expr: [`args.resolverName === "${trigger.resolverName}"`, ...trigger.condition ? [`(${stringifyFunction(trigger.condition)})(${buildResolverExecutedArgsExpr(envField)})`] : []].join(" && ") }
102248
102325
  }
102249
102326
  } };
102250
102327
  break;
@@ -102260,13 +102337,14 @@ function protoExecutor(appName, executor, env) {
102260
102337
  const target = executor.operation;
102261
102338
  let targetType;
102262
102339
  let targetConfig;
102340
+ const argsExpr = trigger.kind === "resolverExecuted" ? buildResolverExecutedArgsExpr(envField) : baseArgsExpr;
102263
102341
  switch (target.kind) {
102264
102342
  case "webhook":
102265
102343
  targetType = ExecutorTargetType.WEBHOOK;
102266
102344
  targetConfig = { config: {
102267
102345
  case: "webhook",
102268
102346
  value: {
102269
- url: { expr: `(${stringifyFunction(target.url)})(args)` },
102347
+ url: { expr: `(${stringifyFunction(target.url)})(${argsExpr})` },
102270
102348
  headers: target.headers ? Object.entries(target.headers).map(([key, v$1]) => {
102271
102349
  let value;
102272
102350
  if (typeof v$1 === "string") value = {
@@ -102285,7 +102363,7 @@ function protoExecutor(appName, executor, env) {
102285
102363
  value
102286
102364
  };
102287
102365
  }) : void 0,
102288
- body: target.requestBody ? { expr: `(${stringifyFunction(target.requestBody)})(args)` } : void 0
102366
+ body: target.requestBody ? { expr: `(${stringifyFunction(target.requestBody)})(${argsExpr})` } : void 0
102289
102367
  }
102290
102368
  } };
102291
102369
  break;
@@ -102296,7 +102374,7 @@ function protoExecutor(appName, executor, env) {
102296
102374
  value: {
102297
102375
  appName: target.appName ?? appName,
102298
102376
  query: target.query,
102299
- variables: target.variables ? { expr: `(${stringifyFunction(target.variables)})(args)` } : void 0,
102377
+ variables: target.variables ? { expr: `(${stringifyFunction(target.variables)})(${argsExpr})` } : void 0,
102300
102378
  invoker: target.authInvoker ?? void 0
102301
102379
  }
102302
102380
  } };
@@ -102312,7 +102390,7 @@ function protoExecutor(appName, executor, env) {
102312
102390
  value: {
102313
102391
  name: `${executor.name}__target`,
102314
102392
  script,
102315
- variables: { expr: `({ ...args, appNamespace: args.namespaceName, env: ${JSON.stringify(env)} })` },
102393
+ variables: { expr: argsExpr },
102316
102394
  invoker: target.authInvoker ?? void 0
102317
102395
  }
102318
102396
  } };
@@ -102324,7 +102402,7 @@ function protoExecutor(appName, executor, env) {
102324
102402
  case: "workflow",
102325
102403
  value: {
102326
102404
  workflowName: target.workflowName,
102327
- variables: target.args ? typeof target.args === "function" ? { expr: `(${stringifyFunction(target.args)})(args)` } : { expr: JSON.stringify(target.args) } : void 0,
102405
+ variables: target.args ? typeof target.args === "function" ? { expr: `(${stringifyFunction(target.args)})(${argsExpr})` } : { expr: JSON.stringify(target.args) } : void 0,
102328
102406
  invoker: target.authInvoker ?? void 0
102329
102407
  }
102330
102408
  } };
@@ -102413,7 +102491,7 @@ async function planPipeline({ client, workspaceId, application, forRemoval }) {
102413
102491
  resourceOwners
102414
102492
  };
102415
102493
  }
102416
- function trn$3(workspaceId, name$1) {
102494
+ function trn$2(workspaceId, name$1) {
102417
102495
  return `trn:v1:workspace:${workspaceId}:pipeline:${name$1}`;
102418
102496
  }
102419
102497
  async function planServices$1(client, workspaceId, appName, pipelines) {
@@ -102436,7 +102514,7 @@ async function planServices$1(client, workspaceId, appName, pipelines) {
102436
102514
  const existingServices = {};
102437
102515
  await Promise.all(withoutLabel.map(async (resource) => {
102438
102516
  if (!resource.namespace?.name) return;
102439
- const { metadata } = await client.getMetadata({ trn: trn$3(workspaceId, resource.namespace.name) });
102517
+ const { metadata } = await client.getMetadata({ trn: trn$2(workspaceId, resource.namespace.name) });
102440
102518
  existingServices[resource.namespace.name] = {
102441
102519
  resource,
102442
102520
  label: metadata?.labels[sdkNameLabelKey]
@@ -102444,7 +102522,7 @@ async function planServices$1(client, workspaceId, appName, pipelines) {
102444
102522
  }));
102445
102523
  for (const pipeline of pipelines) {
102446
102524
  const existing = existingServices[pipeline.namespace];
102447
- const metaRequest = await buildMetaRequest(trn$3(workspaceId, pipeline.namespace), appName);
102525
+ const metaRequest = await buildMetaRequest(trn$2(workspaceId, pipeline.namespace), appName);
102448
102526
  if (existing) {
102449
102527
  if (!existing.label) unmanaged.push({
102450
102528
  resourceType: "Pipeline service",
@@ -102637,7 +102715,7 @@ async function applyStaticWebsite(client, result, phase = "create-update") {
102637
102715
  })]);
102638
102716
  else if (phase === "delete") await Promise.all(changeSet.deletes.map((del) => client.deleteStaticWebsite(del.request)));
102639
102717
  }
102640
- function trn$2(workspaceId, name$1) {
102718
+ function trn$1(workspaceId, name$1) {
102641
102719
  return `trn:v1:workspace:${workspaceId}:staticwebsite:${name$1}`;
102642
102720
  }
102643
102721
  async function planStaticWebsite({ client, workspaceId, application, forRemoval }) {
@@ -102659,7 +102737,7 @@ async function planStaticWebsite({ client, workspaceId, application, forRemoval
102659
102737
  });
102660
102738
  const existingWebsites = {};
102661
102739
  await Promise.all(withoutLabel.map(async (resource) => {
102662
- const { metadata } = await client.getMetadata({ trn: trn$2(workspaceId, resource.name) });
102740
+ const { metadata } = await client.getMetadata({ trn: trn$1(workspaceId, resource.name) });
102663
102741
  existingWebsites[resource.name] = {
102664
102742
  resource,
102665
102743
  label: metadata?.labels[sdkNameLabelKey]
@@ -102670,7 +102748,7 @@ async function planStaticWebsite({ client, workspaceId, application, forRemoval
102670
102748
  const config = websiteService;
102671
102749
  const name$1 = websiteService.name;
102672
102750
  const existing = existingWebsites[name$1];
102673
- const metaRequest = await buildMetaRequest(trn$2(workspaceId, name$1), application.name);
102751
+ const metaRequest = await buildMetaRequest(trn$1(workspaceId, name$1), application.name);
102674
102752
  if (existing) {
102675
102753
  if (!existing.label) unmanaged.push({
102676
102754
  resourceType: "StaticWebsite",
@@ -102768,7 +102846,7 @@ async function planTailorDB({ client, workspaceId, application, forRemoval }) {
102768
102846
  resourceOwners
102769
102847
  };
102770
102848
  }
102771
- function trn$1(workspaceId, name$1) {
102849
+ function trn(workspaceId, name$1) {
102772
102850
  return `${trnPrefix(workspaceId)}:tailordb:${name$1}`;
102773
102851
  }
102774
102852
  async function planServices(client, workspaceId, appName, tailordbs) {
@@ -102791,7 +102869,7 @@ async function planServices(client, workspaceId, appName, tailordbs) {
102791
102869
  const existingServices = {};
102792
102870
  await Promise.all(withoutLabel.map(async (resource) => {
102793
102871
  if (!resource.namespace?.name) return;
102794
- const { metadata } = await client.getMetadata({ trn: trn$1(workspaceId, resource.namespace.name) });
102872
+ const { metadata } = await client.getMetadata({ trn: trn(workspaceId, resource.namespace.name) });
102795
102873
  existingServices[resource.namespace.name] = {
102796
102874
  resource,
102797
102875
  label: metadata?.labels[sdkNameLabelKey]
@@ -102799,7 +102877,7 @@ async function planServices(client, workspaceId, appName, tailordbs) {
102799
102877
  }));
102800
102878
  for (const tailordb of tailordbs) {
102801
102879
  const existing = existingServices[tailordb.namespace];
102802
- const metaRequest = await buildMetaRequest(trn$1(workspaceId, tailordb.namespace), appName);
102880
+ const metaRequest = await buildMetaRequest(trn(workspaceId, tailordb.namespace), appName);
102803
102881
  if (existing) {
102804
102882
  if (!existing.label) unmanaged.push({
102805
102883
  resourceType: "TailorDB service",
@@ -103272,9 +103350,9 @@ function protoGqlOperand(operand) {
103272
103350
  //#endregion
103273
103351
  //#region src/cli/apply/services/workflow.ts
103274
103352
  async function applyWorkflow(client, result, phase = "create-update") {
103275
- const { changeSet } = result;
103353
+ const { changeSet, appName } = result;
103276
103354
  if (phase === "create-update") {
103277
- const jobFunctionVersions = await registerJobFunctions(client, changeSet);
103355
+ const jobFunctionVersions = await registerJobFunctions(client, changeSet, appName);
103278
103356
  await Promise.all([...changeSet.creates.map(async (create$1) => {
103279
103357
  const filteredVersions = filterJobFunctionVersions(jobFunctionVersions, create$1.usedJobNames);
103280
103358
  await client.createWorkflow({
@@ -103311,44 +103389,58 @@ function filterJobFunctionVersions(allVersions, usedJobNames) {
103311
103389
  * Register job functions used by any workflow.
103312
103390
  * Only registers jobs that are actually used (based on usedJobNames in changeSet).
103313
103391
  * Uses create for new jobs and update for existing jobs.
103392
+ * Sets metadata on used JobFunctions and removes metadata from unused ones.
103314
103393
  */
103315
- async function registerJobFunctions(client, changeSet) {
103394
+ async function registerJobFunctions(client, changeSet, appName) {
103316
103395
  const jobFunctionVersions = {};
103317
103396
  const firstWorkflow = changeSet.creates[0] || changeSet.updates[0];
103318
103397
  if (!firstWorkflow) return jobFunctionVersions;
103319
103398
  const { workspaceId, scripts } = firstWorkflow;
103320
103399
  const allUsedJobNames = /* @__PURE__ */ new Set();
103321
103400
  for (const item of [...changeSet.creates, ...changeSet.updates]) for (const jobName of item.usedJobNames) allUsedJobNames.add(jobName);
103322
- const existingJobNames = await fetchAll(async (pageToken) => {
103401
+ const existingJobFunctions = await fetchAll(async (pageToken) => {
103323
103402
  const response = await client.listWorkflowJobFunctions({
103324
103403
  workspaceId,
103325
103404
  pageToken
103326
103405
  });
103327
103406
  return [response.jobFunctions.map((j) => j.name), response.nextPageToken];
103328
103407
  });
103329
- const existingJobNamesSet = new Set(existingJobNames);
103408
+ const existingJobNamesSet = new Set(existingJobFunctions);
103330
103409
  const results = await Promise.all(Array.from(allUsedJobNames).map(async (jobName) => {
103331
103410
  const script = scripts.get(jobName);
103332
103411
  if (!script) throw new Error(`No bundled script found for job "${jobName}". Please run "generate" command before "apply".`);
103412
+ const response = existingJobNamesSet.has(jobName) ? await client.updateWorkflowJobFunction({
103413
+ workspaceId,
103414
+ jobFunctionName: jobName,
103415
+ script
103416
+ }) : await client.createWorkflowJobFunction({
103417
+ workspaceId,
103418
+ jobFunctionName: jobName,
103419
+ script
103420
+ });
103421
+ await client.setMetadata(await buildMetaRequest(jobFunctionTrn(workspaceId, jobName), appName));
103333
103422
  return {
103334
103423
  jobName,
103335
- version: (existingJobNamesSet.has(jobName) ? await client.updateWorkflowJobFunction({
103336
- workspaceId,
103337
- jobFunctionName: jobName,
103338
- script
103339
- }) : await client.createWorkflowJobFunction({
103340
- workspaceId,
103341
- jobFunctionName: jobName,
103342
- script
103343
- })).jobFunction?.version
103424
+ version: response.jobFunction?.version
103344
103425
  };
103345
103426
  }));
103346
103427
  for (const { jobName, version: version$4 } of results) if (version$4) jobFunctionVersions[jobName] = version$4;
103428
+ const unusedJobFunctions = existingJobFunctions.filter((jobName) => !allUsedJobNames.has(jobName));
103429
+ await Promise.all(unusedJobFunctions.map(async (jobName) => {
103430
+ const { metadata } = await client.getMetadata({ trn: jobFunctionTrn(workspaceId, jobName) });
103431
+ if (metadata?.labels?.[sdkNameLabelKey] === appName) await client.setMetadata({
103432
+ trn: jobFunctionTrn(workspaceId, jobName),
103433
+ labels: { [sdkNameLabelKey]: "" }
103434
+ });
103435
+ }));
103347
103436
  return jobFunctionVersions;
103348
103437
  }
103349
- function trn(workspaceId, name$1) {
103438
+ function workflowTrn(workspaceId, name$1) {
103350
103439
  return `trn:v1:workspace:${workspaceId}:workflow:${name$1}`;
103351
103440
  }
103441
+ function jobFunctionTrn(workspaceId, name$1) {
103442
+ return `trn:v1:workspace:${workspaceId}:workflow_job_function:${name$1}`;
103443
+ }
103352
103444
  async function planWorkflow(client, workspaceId, appName, workflows, mainJobDeps) {
103353
103445
  const changeSet = new ChangeSet("Workflows");
103354
103446
  const conflicts = [];
@@ -103366,7 +103458,7 @@ async function planWorkflow(client, workspaceId, appName, workflows, mainJobDeps
103366
103458
  });
103367
103459
  const existingWorkflows = {};
103368
103460
  await Promise.all(withoutLabel.map(async (resource) => {
103369
- const { metadata } = await client.getMetadata({ trn: trn(workspaceId, resource.name) });
103461
+ const { metadata } = await client.getMetadata({ trn: workflowTrn(workspaceId, resource.name) });
103370
103462
  existingWorkflows[resource.name] = {
103371
103463
  resource,
103372
103464
  label: metadata?.labels[sdkNameLabelKey]
@@ -103375,7 +103467,7 @@ async function planWorkflow(client, workspaceId, appName, workflows, mainJobDeps
103375
103467
  const allScripts = await loadWorkflowScripts();
103376
103468
  for (const workflow of Object.values(workflows)) {
103377
103469
  const existing = existingWorkflows[workflow.name];
103378
- const metaRequest = await buildMetaRequest(trn(workspaceId, workflow.name), appName);
103470
+ const metaRequest = await buildMetaRequest(workflowTrn(workspaceId, workflow.name), appName);
103379
103471
  const usedJobNames = mainJobDeps[workflow.mainJob.name];
103380
103472
  if (!usedJobNames) throw new Error(`No dependency info found for mainJob "${workflow.mainJob.name}". Please run "generate" command before "apply".`);
103381
103473
  if (existing) {
@@ -103420,7 +103512,8 @@ async function planWorkflow(client, workspaceId, appName, workflows, mainJobDeps
103420
103512
  changeSet,
103421
103513
  conflicts,
103422
103514
  unmanaged,
103423
- resourceOwners
103515
+ resourceOwners,
103516
+ appName
103424
103517
  };
103425
103518
  }
103426
103519
  async function loadWorkflowScripts() {
@@ -104073,7 +104166,6 @@ var GenerationManager = class {
104073
104166
  async generate(watch) {
104074
104167
  logger.newline();
104075
104168
  logger.log(`Generation for application: ${styles.highlight(this.application.config.name)}`);
104076
- logger.newline();
104077
104169
  const app = this.application;
104078
104170
  for (const db of app.tailorDBServices) {
104079
104171
  const namespace = db.namespace;
@@ -104365,42 +104457,6 @@ const generateCommand = defineCommand({
104365
104457
  })
104366
104458
  });
104367
104459
 
104368
- //#endregion
104369
- //#region src/cli/utils/format.ts
104370
- function humanizeRelativeTime(isoString) {
104371
- const date = new Date(isoString);
104372
- if (Number.isNaN(date.getTime())) return isoString;
104373
- return formatDistanceToNowStrict(date, { addSuffix: true });
104374
- }
104375
- function printData(data$1, json = false) {
104376
- if (json) {
104377
- console.log(JSON.stringify(data$1));
104378
- return;
104379
- }
104380
- if (!Array.isArray(data$1)) {
104381
- const t$2 = table(Object.entries(data$1), {
104382
- singleLine: true,
104383
- border: getBorderCharacters("norc")
104384
- });
104385
- process.stdout.write(t$2);
104386
- return;
104387
- }
104388
- if (data$1.length === 0) return;
104389
- const headers = Array.from(new Set(data$1.flatMap((item) => Object.keys(item))));
104390
- const t$1 = table([headers, ...data$1.map((item) => headers.map((header) => {
104391
- const value = item[header];
104392
- if (value === null || value === void 0) return "";
104393
- if ((header === "createdAt" || header === "updatedAt") && typeof value === "string") return humanizeRelativeTime(value);
104394
- return String(value);
104395
- }))], {
104396
- border: getBorderCharacters("norc"),
104397
- drawHorizontalLine: (lineIndex, rowCount) => {
104398
- return lineIndex === 0 || lineIndex === 1 || lineIndex === rowCount;
104399
- }
104400
- });
104401
- process.stdout.write(t$1);
104402
- }
104403
-
104404
104460
  //#endregion
104405
104461
  //#region src/cli/machineuser/list.ts
104406
104462
  function machineUserInfo(user) {
@@ -104447,11 +104503,12 @@ const listCommand$3 = defineCommand({
104447
104503
  ...deploymentArgs
104448
104504
  },
104449
104505
  run: withCommonArgs(async (args) => {
104450
- printData(await listMachineUsers({
104506
+ const machineUsers = await listMachineUsers({
104451
104507
  workspaceId: args["workspace-id"],
104452
104508
  profile: args.profile,
104453
104509
  configPath: args.config
104454
- }), args.json);
104510
+ });
104511
+ logger.out(machineUsers);
104455
104512
  })
104456
104513
  });
104457
104514
 
@@ -104509,11 +104566,12 @@ const tokenCommand = defineCommand({
104509
104566
  profile: args.profile,
104510
104567
  configPath: args.config
104511
104568
  });
104512
- printData({
104569
+ const tokenInfo = {
104513
104570
  access_token: token.accessToken,
104514
104571
  token_type: token.tokenType,
104515
104572
  expires_at: token.expiresAt
104516
- }, args.json);
104573
+ };
104574
+ logger.out(tokenInfo);
104517
104575
  })
104518
104576
  });
104519
104577
 
@@ -104593,12 +104651,13 @@ const getCommand$1 = defineCommand({
104593
104651
  }
104594
104652
  },
104595
104653
  run: withCommonArgs(async (args) => {
104596
- printData(await getOAuth2Client({
104654
+ const credentials = await getOAuth2Client({
104597
104655
  name: args.name,
104598
104656
  workspaceId: args["workspace-id"],
104599
104657
  profile: args.profile,
104600
104658
  configPath: args.config
104601
- }), args.json);
104659
+ });
104660
+ logger.out(credentials);
104602
104661
  })
104603
104662
  });
104604
104663
 
@@ -104639,11 +104698,12 @@ const listCommand$2 = defineCommand({
104639
104698
  ...deploymentArgs
104640
104699
  },
104641
104700
  run: withCommonArgs(async (args) => {
104642
- printData(await listOAuth2Clients({
104701
+ const oauth2Clients = await listOAuth2Clients({
104643
104702
  workspaceId: args["workspace-id"],
104644
104703
  profile: args.profile,
104645
104704
  configPath: args.config
104646
- }), args.json);
104705
+ });
104706
+ logger.out(oauth2Clients);
104647
104707
  })
104648
104708
  });
104649
104709
 
@@ -104808,14 +104868,48 @@ const showCommand = defineCommand({
104808
104868
  }
104809
104869
  },
104810
104870
  run: withCommonArgs(async (args) => {
104811
- printData(await show({
104871
+ const appInfo = await show({
104812
104872
  workspaceId: args["workspace-id"],
104813
104873
  profile: args.profile,
104814
104874
  configPath: args.config
104815
- }), args.json);
104875
+ });
104876
+ logger.out(appInfo);
104816
104877
  })
104817
104878
  });
104818
104879
 
104880
+ //#endregion
104881
+ //#region src/cli/utils/format.ts
104882
+ /**
104883
+ * Formats a table with consistent single-line border style.
104884
+ * Use this instead of importing `table` directly.
104885
+ */
104886
+ function formatTable(data$1, config) {
104887
+ return table(data$1, {
104888
+ ...config,
104889
+ border: getBorderCharacters("norc")
104890
+ });
104891
+ }
104892
+ /**
104893
+ * Formats a key-value table with single-line border style.
104894
+ */
104895
+ function formatKeyValueTable(data$1) {
104896
+ return formatTable(data$1, { singleLine: true });
104897
+ }
104898
+ /**
104899
+ * Formats a table with headers, using single-line border style.
104900
+ * Draws horizontal lines only at top, after header, and bottom.
104901
+ */
104902
+ function formatTableWithHeaders(headers, rows) {
104903
+ return formatTable([headers, ...rows], { drawHorizontalLine: (lineIndex, rowCount) => {
104904
+ return lineIndex === 0 || lineIndex === 1 || lineIndex === rowCount;
104905
+ } });
104906
+ }
104907
+ function humanizeRelativeTime(isoString) {
104908
+ const date = new Date(isoString);
104909
+ if (Number.isNaN(date.getTime())) return isoString;
104910
+ return formatDistanceToNowStrict(date, { addSuffix: true });
104911
+ }
104912
+
104819
104913
  //#endregion
104820
104914
  //#region src/cli/workflow/args.ts
104821
104915
  const nameArgs = { name: {
@@ -105066,7 +105160,7 @@ function printExecutionWithLogs(execution) {
105066
105160
  ["startedAt", execution.startedAt],
105067
105161
  ["finishedAt", execution.finishedAt]
105068
105162
  ];
105069
- process.stdout.write(table(summaryData, { singleLine: true }));
105163
+ logger.out(formatKeyValueTable(summaryData));
105070
105164
  if (execution.jobDetails && execution.jobDetails.length > 0) {
105071
105165
  logger.log(styles.bold("\nJob Executions:"));
105072
105166
  for (const job of execution.jobDetails) {
@@ -105135,13 +105229,16 @@ const executionsCommand = defineCommand({
105135
105229
  if (!args.json) logger.info(`Execution ID: ${execution.id}`, { mode: "stream" });
105136
105230
  const result = args.wait ? await waitWithSpinner(wait, interval, args.json) : execution;
105137
105231
  if (args.logs && !args.json) printExecutionWithLogs(result);
105138
- else printData(result, args.json);
105139
- } else printData(await listWorkflowExecutions({
105140
- workspaceId: args["workspace-id"],
105141
- profile: args.profile,
105142
- workflowName: args["workflow-name"],
105143
- status: args.status
105144
- }), args.json);
105232
+ else logger.out(result);
105233
+ } else {
105234
+ const executions = await listWorkflowExecutions({
105235
+ workspaceId: args["workspace-id"],
105236
+ profile: args.profile,
105237
+ workflowName: args["workflow-name"],
105238
+ status: args.status
105239
+ });
105240
+ logger.out(executions);
105241
+ }
105145
105242
  })
105146
105243
  });
105147
105244
 
@@ -105183,11 +105280,12 @@ const getCommand = defineCommand({
105183
105280
  ...nameArgs
105184
105281
  },
105185
105282
  run: withCommonArgs(async (args) => {
105186
- printData(await getWorkflow({
105283
+ const workflow = await getWorkflow({
105187
105284
  name: args.name,
105188
105285
  workspaceId: args["workspace-id"],
105189
105286
  profile: args.profile
105190
- }), args.json);
105287
+ });
105288
+ logger.out(workflow);
105191
105289
  })
105192
105290
  });
105193
105291
 
@@ -105225,7 +105323,7 @@ const listCommand$1 = defineCommand({
105225
105323
  workspaceId: args["workspace-id"],
105226
105324
  profile: args.profile
105227
105325
  });
105228
- if (args.json) printData(workflows, args.json);
105326
+ if (args.json) logger.out(workflows);
105229
105327
  else {
105230
105328
  if (workflows.length === 0) {
105231
105329
  logger.info("No workflows found.");
@@ -105243,7 +105341,7 @@ const listCommand$1 = defineCommand({
105243
105341
  w.jobFunctions.toString(),
105244
105342
  humanizeRelativeTime(w.updatedAt)
105245
105343
  ]);
105246
- process.stdout.write(table([headers, ...rows]));
105344
+ logger.out(formatTableWithHeaders(headers, rows));
105247
105345
  }
105248
105346
  })
105249
105347
  });
@@ -105401,9 +105499,9 @@ const startCommand = defineCommand({
105401
105499
  configPath: args.config,
105402
105500
  interval
105403
105501
  });
105404
- if (!args.json) logger.info(`Execution ID: ${executionId}`, { mode: "stream" });
105502
+ logger.info(`Execution ID: ${executionId}`, { mode: "stream" });
105405
105503
  if (args.wait) {
105406
- const result = await wait({ showProgress: !args.json });
105504
+ const result = await wait({ showProgress: true });
105407
105505
  if (args.logs && !args.json) {
105408
105506
  const { execution } = await getWorkflowExecution({
105409
105507
  executionId,
@@ -105412,8 +105510,8 @@ const startCommand = defineCommand({
105412
105510
  logs: true
105413
105511
  });
105414
105512
  printExecutionWithLogs(execution);
105415
- } else printData(result, args.json);
105416
- } else printData({ executionId }, args.json);
105513
+ } else logger.out(result);
105514
+ } else logger.out({ executionId });
105417
105515
  })
105418
105516
  });
105419
105517
 
@@ -105486,8 +105584,8 @@ const resumeCommand = defineCommand({
105486
105584
  logs: true
105487
105585
  });
105488
105586
  printExecutionWithLogs(execution);
105489
- } else printData(result, args.json);
105490
- } else printData({ executionId }, args.json);
105587
+ } else logger.out(result);
105588
+ } else logger.out({ executionId });
105491
105589
  })
105492
105590
  });
105493
105591
 
@@ -105583,7 +105681,7 @@ const createCommand = defineCommand({
105583
105681
  folderId: args["folder-id"]
105584
105682
  });
105585
105683
  if (!args.json) logger.success(`Workspace "${args.name}" created successfully.`);
105586
- printData(workspace, args.json);
105684
+ logger.out(workspace);
105587
105685
  })
105588
105686
  });
105589
105687
 
@@ -105688,13 +105786,14 @@ const listCommand = defineCommand({
105688
105786
  throw new Error(`--limit must be a positive integer, got '${args.limit}'`);
105689
105787
  }
105690
105788
  const workspaces = await listWorkspaces({ limit });
105691
- printData(args.json ? workspaces : workspaces.map(({ updatedAt: _$1, createdAt, ...rest }) => ({
105789
+ const formattedWorkspaces = args.json ? workspaces : workspaces.map(({ updatedAt: _$1, createdAt, ...rest }) => ({
105692
105790
  ...rest,
105693
105791
  createdAt: humanizeRelativeTime(createdAt)
105694
- })), args.json);
105792
+ }));
105793
+ logger.out(formattedWorkspaces);
105695
105794
  })
105696
105795
  });
105697
105796
 
105698
105797
  //#endregion
105699
- export { jsonArgs as $, printData as A, loadAccessToken as B, listOAuth2Clients as C, tokenCommand as D, getMachineUserToken as E, generateUserTypes as F, fetchUserInfo as G, readPlatformConfig as H, loadConfig as I, readPackageJson as J, initOAuth2Client as K, apiCall as L, generateCommand as M, apply as N, listCommand$3 as O, applyCommand as P, deploymentArgs as Q, apiCommand as R, listCommand$2 as S, getOAuth2Client as T, writePlatformConfig as U, loadWorkspaceId as V, fetchAll as W, commonArgs as X, PATScope as Y, confirmationArgs as Z, listWorkflowExecutions as _, createCommand as a, remove as b, resumeWorkflow as c, listCommand$1 as d, withCommonArgs as et, listWorkflows as f, getWorkflowExecution as g, executionsCommand as h, deleteWorkspace as i, generate as j, listMachineUsers as k, startCommand as l, getWorkflow as m, listWorkspaces as n, logger as nt, createWorkspace as o, getCommand as p, initOperatorClient as q, deleteCommand as r, resumeCommand as s, listCommand as t, workspaceArgs as tt, startWorkflow as u, show as v, getCommand$1 as w, removeCommand as x, showCommand as y, fetchLatestToken as z };
105700
- //# sourceMappingURL=list-BticEhbi.mjs.map
105798
+ export { withCommonArgs as $, generate as A, loadWorkspaceId as B, listOAuth2Clients as C, tokenCommand as D, getMachineUserToken as E, loadConfig as F, initOAuth2Client as G, writePlatformConfig as H, apiCall as I, PATScope as J, initOperatorClient as K, apiCommand as L, apply as M, applyCommand as N, listCommand$3 as O, generateUserTypes as P, jsonArgs as Q, fetchLatestToken as R, listCommand$2 as S, getOAuth2Client as T, fetchAll as U, readPlatformConfig as V, fetchUserInfo as W, confirmationArgs as X, commonArgs as Y, deploymentArgs as Z, listWorkflowExecutions as _, createCommand as a, remove as b, resumeWorkflow as c, listCommand$1 as d, workspaceArgs as et, listWorkflows as f, getWorkflowExecution as g, executionsCommand as h, deleteWorkspace as i, generateCommand as j, listMachineUsers as k, startCommand as l, getWorkflow as m, listWorkspaces as n, createWorkspace as o, getCommand as p, readPackageJson as q, deleteCommand as r, resumeCommand as s, listCommand as t, logger as tt, startWorkflow as u, show as v, getCommand$1 as w, removeCommand as x, showCommand as y, loadAccessToken as z };
105799
+ //# sourceMappingURL=list-9sLkfPfn.mjs.map