@apso/cli 0.52.0 → 0.54.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.
Files changed (106) hide show
  1. package/dist/commands/import/supabase.js +31 -6
  2. package/dist/commands/init.d.ts +9 -0
  3. package/dist/commands/init.js +31 -1
  4. package/dist/commands/mcp/serve.js +20 -0
  5. package/dist/commands/schema/validate.js +18 -1
  6. package/dist/lib/apsorc-parser.js +7 -3
  7. package/dist/lib/base-command.js +14 -3
  8. package/dist/lib/config/types.d.ts +5 -0
  9. package/dist/lib/ddl/catalog.js +5 -2
  10. package/dist/lib/ddl/change.js +13 -2
  11. package/dist/lib/ddl/index.d.ts +62 -3
  12. package/dist/lib/ddl/index.js +211 -40
  13. package/dist/lib/generators/go.js +17 -3
  14. package/dist/lib/generators/python.js +17 -3
  15. package/dist/lib/generators/typescript.js +85 -15
  16. package/dist/lib/import/copy-data.js +4 -0
  17. package/dist/lib/import/introspect.d.ts +40 -0
  18. package/dist/lib/import/introspect.js +137 -49
  19. package/dist/lib/import/pg-to-apsorc.d.ts +62 -0
  20. package/dist/lib/import/pg-to-apsorc.js +248 -37
  21. package/dist/lib/import/types.d.ts +48 -3
  22. package/dist/lib/migrate/sandbox.js +23 -6
  23. package/dist/lib/migrate/snapshot.d.ts +5 -0
  24. package/dist/lib/plan/index.d.ts +4 -1
  25. package/dist/lib/plan/index.js +9 -3
  26. package/dist/lib/telemetry/error-utils.d.ts +74 -0
  27. package/dist/lib/telemetry/error-utils.js +221 -0
  28. package/dist/lib/telemetry/internal-constants.d.ts +27 -0
  29. package/dist/lib/telemetry/internal-constants.js +32 -0
  30. package/dist/lib/telemetry/internal-detection.d.ts +37 -0
  31. package/dist/lib/telemetry/internal-detection.js +78 -0
  32. package/dist/lib/telemetry/telemetry.d.ts +11 -0
  33. package/dist/lib/telemetry/telemetry.js +197 -3
  34. package/dist/lib/templates/entities/entity-col-array.eta +2 -1
  35. package/dist/lib/templates/entities/entity-col-bigint.eta +2 -2
  36. package/dist/lib/templates/entities/entity-col-bigserial.eta +2 -2
  37. package/dist/lib/templates/entities/entity-col-boolean.eta +1 -1
  38. package/dist/lib/templates/entities/entity-col-bytea.eta +2 -2
  39. package/dist/lib/templates/entities/entity-col-char.eta +4 -3
  40. package/dist/lib/templates/entities/entity-col-date.eta +6 -2
  41. package/dist/lib/templates/entities/entity-col-datetime.eta +8 -1
  42. package/dist/lib/templates/entities/entity-col-decimal.eta +2 -2
  43. package/dist/lib/templates/entities/entity-col-double.eta +2 -2
  44. package/dist/lib/templates/entities/entity-col-float.eta +1 -1
  45. package/dist/lib/templates/entities/entity-col-geography.eta +1 -1
  46. package/dist/lib/templates/entities/entity-col-geometry.eta +1 -1
  47. package/dist/lib/templates/entities/entity-col-geometrycollection.eta +1 -1
  48. package/dist/lib/templates/entities/entity-col-inet.eta +2 -2
  49. package/dist/lib/templates/entities/entity-col-int4range.eta +1 -1
  50. package/dist/lib/templates/entities/entity-col-integer.eta +2 -2
  51. package/dist/lib/templates/entities/entity-col-interval.eta +2 -2
  52. package/dist/lib/templates/entities/entity-col-json-plain.eta +1 -1
  53. package/dist/lib/templates/entities/entity-col-json.eta +1 -1
  54. package/dist/lib/templates/entities/entity-col-jsonb.eta +1 -1
  55. package/dist/lib/templates/entities/entity-col-linestring.eta +1 -1
  56. package/dist/lib/templates/entities/entity-col-money.eta +2 -2
  57. package/dist/lib/templates/entities/entity-col-multilinestring.eta +1 -1
  58. package/dist/lib/templates/entities/entity-col-multipoint.eta +1 -1
  59. package/dist/lib/templates/entities/entity-col-multipolygon.eta +1 -1
  60. package/dist/lib/templates/entities/entity-col-numeric.eta +2 -2
  61. package/dist/lib/templates/entities/entity-col-point.eta +1 -1
  62. package/dist/lib/templates/entities/entity-col-polygon.eta +1 -1
  63. package/dist/lib/templates/entities/entity-col-real.eta +2 -2
  64. package/dist/lib/templates/entities/entity-col-serial.eta +2 -2
  65. package/dist/lib/templates/entities/entity-col-smallint.eta +2 -2
  66. package/dist/lib/templates/entities/entity-col-smallserial.eta +2 -2
  67. package/dist/lib/templates/entities/entity-col-string.eta +2 -2
  68. package/dist/lib/templates/entities/entity-col-text.eta +4 -3
  69. package/dist/lib/templates/entities/entity-col-time.eta +2 -2
  70. package/dist/lib/templates/entities/entity-col-timestamp.eta +8 -1
  71. package/dist/lib/templates/entities/entity-col-timestamptz.eta +8 -1
  72. package/dist/lib/templates/entities/entity-col-timetz.eta +2 -2
  73. package/dist/lib/templates/entities/entity-col-tsvector.eta +2 -2
  74. package/dist/lib/templates/entities/entity-col-uuid.eta +5 -2
  75. package/dist/lib/templates/entities/entity-col-varchar.eta +4 -3
  76. package/dist/lib/templates/entities/entity-col-xml.eta +2 -2
  77. package/dist/lib/templates/entities/entity.eta +30 -18
  78. package/dist/lib/templates/go/models/model.eta +3 -3
  79. package/dist/lib/templates/python/models/model.eta +1 -1
  80. package/dist/lib/templates/rest/controller-rest.eta +16 -5
  81. package/dist/lib/templates/rest/dto-rest.eta +2 -2
  82. package/dist/lib/templates/rest/index-module-rest.eta +6 -0
  83. package/dist/lib/templates/rest/schema-extras-module.eta +24 -0
  84. package/dist/lib/types/constraints.d.ts +13 -0
  85. package/dist/lib/types/entity.d.ts +67 -2
  86. package/dist/lib/types/entity.js +39 -1
  87. package/dist/lib/types/field.d.ts +20 -2
  88. package/dist/lib/types/indices.d.ts +21 -0
  89. package/dist/lib/types/relationship.d.ts +33 -0
  90. package/dist/lib/types/relationship.js +13 -0
  91. package/dist/lib/upgrade.d.ts +5 -6
  92. package/dist/lib/upgrade.js +12 -23
  93. package/dist/lib/utils/field.d.ts +22 -0
  94. package/dist/lib/utils/field.js +62 -3
  95. package/dist/lib/utils/relationships/index.d.ts +1 -1
  96. package/dist/lib/utils/relationships/index.js +2 -1
  97. package/dist/lib/utils/relationships/parse.d.ts +11 -0
  98. package/dist/lib/utils/relationships/parse.js +44 -1
  99. package/dist/lib/utils/template.d.ts +3 -3
  100. package/dist/lib/utils/template.js +4 -4
  101. package/dist/lib/verify/crud-plan.d.ts +2 -0
  102. package/dist/lib/verify/crud-plan.js +19 -5
  103. package/dist/lib/verify/index.js +32 -3
  104. package/npm-shrinkwrap.json +77 -91
  105. package/oclif.manifest.json +7 -1
  106. package/package.json +4 -2
@@ -17,6 +17,8 @@ const fs = tslib_1.__importStar(require("fs"));
17
17
  const path = tslib_1.__importStar(require("path"));
18
18
  const paths_1 = require("../config/paths");
19
19
  const snapshot_1 = require("./snapshot");
20
+ const entity_1 = require("../types/entity");
21
+ const relationship_1 = require("../types/relationship");
20
22
  const field_1 = require("../utils/field");
21
23
  const casing_1 = require("../utils/casing");
22
24
  const relationships_1 = require("../utils/relationships");
@@ -87,10 +89,16 @@ function buildEntityClasses(entities, relationshipMap = {}) {
87
89
  }
88
90
  }
89
91
  if (entityDef.created_at) {
90
- typeorm.CreateDateColumn()(EntityClass.prototype, "created_at");
92
+ typeorm.CreateDateColumn({
93
+ type: (0, entity_1.timestampTypeOf)(entityDef, "created_at"),
94
+ nullable: (0, entity_1.timestampNullableOf)(entityDef, "created_at"),
95
+ })(EntityClass.prototype, "created_at");
91
96
  }
92
97
  if (entityDef.updated_at) {
93
- typeorm.UpdateDateColumn()(EntityClass.prototype, "updated_at");
98
+ typeorm.UpdateDateColumn({
99
+ type: (0, entity_1.timestampTypeOf)(entityDef, "updated_at"),
100
+ nullable: (0, entity_1.timestampNullableOf)(entityDef, "updated_at"),
101
+ })(EntityClass.prototype, "updated_at");
94
102
  }
95
103
  const fields = entityDef.fields || [];
96
104
  for (const field of fields) {
@@ -108,7 +116,8 @@ function buildEntityClasses(entities, relationshipMap = {}) {
108
116
  if (field.unique)
109
117
  colOpts.unique = true;
110
118
  if (field.default !== undefined && field.default !== null) {
111
- colOpts.default = field.default;
119
+ const sql = (0, field_1.defaultSqlOf)(field);
120
+ colOpts.default = sql === undefined ? field.default : () => sql;
112
121
  }
113
122
  if (field.type === "enum" && field.values) {
114
123
  colOpts.enum = field.values;
@@ -145,8 +154,8 @@ function buildEntityClasses(entities, relationshipMap = {}) {
145
154
  if (relationship.nullable !== undefined) {
146
155
  relationOptions.nullable = relationship.nullable;
147
156
  }
148
- if (relationship.cascadeDelete) {
149
- relationOptions.onDelete = "CASCADE";
157
+ if ((0, relationship_1.onDeleteOf)(relationship)) {
158
+ relationOptions.onDelete = (0, relationship_1.onDeleteOf)(relationship);
150
159
  }
151
160
  if (relationship.type === "ManyToOne") {
152
161
  if (relationship.index) {
@@ -156,7 +165,9 @@ function buildEntityClasses(entities, relationshipMap = {}) {
156
165
  ? (target) => target[inversePropertyName]
157
166
  : undefined;
158
167
  typeorm.ManyToOne(() => targetClass, inverseSide, relationOptions)(EntityClass.prototype, relationship.relationshipName);
159
- typeorm.JoinColumn({ name: relationship.camelCasedId })(EntityClass.prototype, relationship.relationshipName);
168
+ typeorm.JoinColumn({
169
+ name: relationship.joinColumnName || relationship.camelCasedId,
170
+ })(EntityClass.prototype, relationship.relationshipName);
160
171
  }
161
172
  if (relationship.type === "OneToMany" && relationship.biDirectional) {
162
173
  typeorm.OneToMany(() => targetClass, (target) => target[inversePropertyName])(EntityClass.prototype, relationship.pluralizedRelationshipName);
@@ -303,6 +314,8 @@ async function runMigrationSandbox(current, projectDir) {
303
314
  primaryKeyType: e.primaryKeyType,
304
315
  created_at: e.created_at,
305
316
  updated_at: e.updated_at,
317
+ timestampType: e.timestampType,
318
+ timestampNullable: e.timestampNullable,
306
319
  scopeBy: e.scopeBy,
307
320
  });
308
321
  }),
@@ -337,6 +350,8 @@ async function runMigrationSandbox(current, projectDir) {
337
350
  primaryKeyType: se.primaryKeyType,
338
351
  created_at: se.created_at,
339
352
  updated_at: se.updated_at,
353
+ timestampType: se.timestampType,
354
+ timestampNullable: se.timestampNullable,
340
355
  scopeBy: se.scopeBy,
341
356
  });
342
357
  })
@@ -435,6 +450,8 @@ function applyMigration(current, projectDir) {
435
450
  primaryKeyType: e.primaryKeyType,
436
451
  created_at: e.created_at,
437
452
  updated_at: e.updated_at,
453
+ timestampType: e.timestampType,
454
+ timestampNullable: e.timestampNullable,
438
455
  scopeBy: e.scopeBy,
439
456
  });
440
457
  }),
@@ -5,6 +5,7 @@
5
5
  * The snapshot stores the .apsorc content at the time of last successful migration.
6
6
  * Comparing current .apsorc against the snapshot detects whether a migration is needed.
7
7
  */
8
+ import { Entity } from "../types/entity";
8
9
  /**
9
10
  * Shape of the stored snapshot (mirrors the parsed .apsorc structure)
10
11
  */
@@ -22,6 +23,8 @@ export interface ApsorcSnapshot {
22
23
  primaryKeyType?: string;
23
24
  created_at?: boolean;
24
25
  updated_at?: boolean;
26
+ timestampType?: Entity["timestampType"];
27
+ timestampNullable?: Entity["timestampNullable"];
25
28
  scopeBy?: string | string[];
26
29
  }>;
27
30
  relationships?: Array<{
@@ -55,6 +58,8 @@ export interface ComparableSchema {
55
58
  primaryKeyType?: string;
56
59
  created_at?: boolean;
57
60
  updated_at?: boolean;
61
+ timestampType?: Entity["timestampType"];
62
+ timestampNullable?: Entity["timestampNullable"];
58
63
  scopeBy?: string | string[];
59
64
  }>;
60
65
  relationships?: ApsorcSnapshot["relationships"];
@@ -3,8 +3,11 @@ interface PlanField {
3
3
  type: string;
4
4
  values?: string[];
5
5
  nullable?: boolean;
6
- default?: string | null;
6
+ /** A literal, or { sql } for an expression; the plan only asks whether one is set. */
7
+ default?: unknown;
7
8
  elementType?: string;
9
+ /** The expression of a stored generated column. */
10
+ generated?: string;
8
11
  }
9
12
  interface PlanEntity {
10
13
  name: string;
@@ -147,7 +147,8 @@ function planMigration(before, after, previous) {
147
147
  });
148
148
  continue;
149
149
  }
150
- if (!sameType(cur, old)) {
150
+ // Postgres rebuilds a generated column from its expression: no cast.
151
+ if (!sameType(cur, old) && !cur.generated) {
151
152
  questions.push({
152
153
  id: `cast:${now.name}.${old.name}`,
153
154
  kind: "cast",
@@ -168,7 +169,10 @@ function planMigration(before, after, previous) {
168
169
  });
169
170
  }
170
171
  }
171
- if (old.nullable && !cur.nullable && cur.default === undefined) {
172
+ if (old.nullable &&
173
+ !cur.nullable &&
174
+ cur.default === undefined &&
175
+ !cur.generated) {
172
176
  questions.push({
173
177
  id: `backfill:${now.name}.${old.name}`,
174
178
  kind: "backfill",
@@ -222,7 +226,9 @@ function planMigration(before, after, previous) {
222
226
  for (const f of fieldsOf(now)) {
223
227
  if (byName(fieldsOf(was), f.name) ||
224
228
  f.nullable ||
225
- f.default !== undefined)
229
+ f.default !== undefined ||
230
+ // Postgres computes a generated column for the existing rows.
231
+ f.generated)
226
232
  continue;
227
233
  const key = `${now.name}.${f.name}`;
228
234
  if (claimed.has(key) || pending.has(key))
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Error extraction and redaction utilities for telemetry.
3
+ *
4
+ * Extracts useful error properties (class, normalized message, code, entity,
5
+ * field) while redacting sensitive data: file contents, secrets, tokens, env
6
+ * values, and absolute paths. Home-directory paths are redacted.
7
+ */
8
+ /**
9
+ * Maximum number of error messages to include in an array.
10
+ */
11
+ export declare const MAX_ERROR_MESSAGES = 10;
12
+ /**
13
+ * Redact sensitive information from a string.
14
+ */
15
+ export declare function redactSensitiveData(str: string): string;
16
+ /**
17
+ * Truncate a string to a maximum length, adding ellipsis if truncated.
18
+ */
19
+ export declare function truncate(str: string, maxLength?: number): string;
20
+ /**
21
+ * Normalize an error message by redacting sensitive data and truncating.
22
+ */
23
+ export declare function normalizeErrorMessage(message: string): string;
24
+ /**
25
+ * Extract the error class name from an error object.
26
+ */
27
+ export declare function getErrorClass(err: unknown): string | undefined;
28
+ /**
29
+ * Extract the error code from an error object (if present).
30
+ */
31
+ export declare function getErrorCode(err: unknown): string | undefined;
32
+ /**
33
+ * Extract entity name from an error object (for schema/config errors).
34
+ */
35
+ export declare function getErrorEntity(err: unknown): string | undefined;
36
+ /**
37
+ * Extract field name from an error object (for schema/config errors).
38
+ */
39
+ export declare function getErrorField(err: unknown): string | undefined;
40
+ /**
41
+ * Extract error messages array from a validation error.
42
+ * Used for errors that carry multiple individual messages (e.g. ValidationError).
43
+ */
44
+ export declare function getErrorMessages(err: unknown): string[] | undefined;
45
+ /**
46
+ * Extract structured error properties for telemetry.
47
+ *
48
+ * @param err - The error object
49
+ * @returns Object with error properties suitable for telemetry
50
+ */
51
+ export declare function extractErrorProperties(err: unknown): {
52
+ error_class?: string;
53
+ error_message?: string;
54
+ error_code?: string;
55
+ entity?: string;
56
+ field?: string;
57
+ error_messages?: string[];
58
+ };
59
+ /**
60
+ * Extract an array of error messages from multiple errors, redacted and truncated.
61
+ *
62
+ * Used for validation errors where multiple issues may be present.
63
+ *
64
+ * @param errors - Array of errors (strings or Error objects)
65
+ * @param maxCount - Maximum number of error messages to include
66
+ * @returns Array of redacted, truncated error messages
67
+ */
68
+ export declare function extractErrorMessages(errors: Array<string | Error>, maxCount?: number): string[];
69
+ /**
70
+ * Check if an error is a config or validation error (a user error).
71
+ *
72
+ * Config and validation errors should be marked as user errors, not CLI bugs.
73
+ */
74
+ export declare function isConfigOrValidationError(err: unknown): boolean;
@@ -0,0 +1,221 @@
1
+ "use strict";
2
+ /**
3
+ * Error extraction and redaction utilities for telemetry.
4
+ *
5
+ * Extracts useful error properties (class, normalized message, code, entity,
6
+ * field) while redacting sensitive data: file contents, secrets, tokens, env
7
+ * values, and absolute paths. Home-directory paths are redacted.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.isConfigOrValidationError = exports.extractErrorMessages = exports.extractErrorProperties = exports.getErrorMessages = exports.getErrorField = exports.getErrorEntity = exports.getErrorCode = exports.getErrorClass = exports.normalizeErrorMessage = exports.truncate = exports.redactSensitiveData = exports.MAX_ERROR_MESSAGES = void 0;
11
+ const tslib_1 = require("tslib");
12
+ const os_1 = tslib_1.__importDefault(require("os"));
13
+ const apsorc_parser_1 = require("../apsorc-parser");
14
+ /**
15
+ * Sensitive patterns to redact from error messages and properties.
16
+ */
17
+ const SENSITIVE_PATTERNS = [
18
+ // API keys, tokens, secrets (common patterns)
19
+ /\b[\w-]{20,}\b/g,
20
+ /api[_-]?key[\s:=]+\S+/gi,
21
+ /token[\s:=]+\S+/gi,
22
+ /secret[\s:=]+\S+/gi,
23
+ /password[\s:=]+\S+/gi,
24
+ /bearer\s+\S+/gi,
25
+ // Environment variable values
26
+ /\b[A-Z_]+=\S+/g,
27
+ // JWT tokens
28
+ /(?:eyJ[\w-]+\.){2}[\w-]+/g,
29
+ ];
30
+ /**
31
+ * Maximum length for error messages in telemetry (truncate longer messages).
32
+ */
33
+ const MAX_MESSAGE_LENGTH = 500;
34
+ /**
35
+ * Maximum number of error messages to include in an array.
36
+ */
37
+ exports.MAX_ERROR_MESSAGES = 10;
38
+ /**
39
+ * Redact home directory paths from a string, replacing them with ~.
40
+ * Handles both Unix (/) and Windows (\) path separators.
41
+ */
42
+ function redactHomePath(str) {
43
+ const homeDir = os_1.default.homedir();
44
+ if (!homeDir)
45
+ return str;
46
+ // Use split/join for safe replacement (no regex)
47
+ let redacted = str.split(homeDir).join("~");
48
+ // Also handle Windows paths with forward slashes (normalized paths)
49
+ if (os_1.default.platform() === "win32" && homeDir.includes("\\")) {
50
+ const homeDirForward = homeDir.replace(/\\/g, "/");
51
+ redacted = redacted.split(homeDirForward).join("~");
52
+ }
53
+ return redacted;
54
+ }
55
+ /**
56
+ * Redact sensitive information from a string.
57
+ */
58
+ function redactSensitiveData(str) {
59
+ if (!str)
60
+ return str;
61
+ let redacted = str;
62
+ // Redact home directory paths
63
+ redacted = redactHomePath(redacted);
64
+ // Redact sensitive patterns
65
+ for (const pattern of SENSITIVE_PATTERNS) {
66
+ redacted = redacted.replace(pattern, "[REDACTED]");
67
+ }
68
+ return redacted;
69
+ }
70
+ exports.redactSensitiveData = redactSensitiveData;
71
+ /**
72
+ * Truncate a string to a maximum length, adding ellipsis if truncated.
73
+ */
74
+ function truncate(str, maxLength = MAX_MESSAGE_LENGTH) {
75
+ if (!str || str.length <= maxLength)
76
+ return str;
77
+ return str.slice(0, maxLength - 3) + "...";
78
+ }
79
+ exports.truncate = truncate;
80
+ /**
81
+ * Normalize an error message by redacting sensitive data and truncating.
82
+ */
83
+ function normalizeErrorMessage(message) {
84
+ return truncate(redactSensitiveData(message));
85
+ }
86
+ exports.normalizeErrorMessage = normalizeErrorMessage;
87
+ /**
88
+ * Extract the error class name from an error object.
89
+ */
90
+ function getErrorClass(err) {
91
+ if (!err || typeof err !== "object")
92
+ return undefined;
93
+ const constructor = err.constructor;
94
+ return constructor === null || constructor === void 0 ? void 0 : constructor.name;
95
+ }
96
+ exports.getErrorClass = getErrorClass;
97
+ /**
98
+ * Extract the error code from an error object (if present).
99
+ */
100
+ function getErrorCode(err) {
101
+ if (!err || typeof err !== "object")
102
+ return undefined;
103
+ const code = err.code;
104
+ return typeof code === "string" ? code : undefined;
105
+ }
106
+ exports.getErrorCode = getErrorCode;
107
+ /**
108
+ * Extract entity name from an error object (for schema/config errors).
109
+ */
110
+ function getErrorEntity(err) {
111
+ if (!err || typeof err !== "object")
112
+ return undefined;
113
+ const entity = err.entity;
114
+ return typeof entity === "string" ? entity : undefined;
115
+ }
116
+ exports.getErrorEntity = getErrorEntity;
117
+ /**
118
+ * Extract field name from an error object (for schema/config errors).
119
+ */
120
+ function getErrorField(err) {
121
+ if (!err || typeof err !== "object")
122
+ return undefined;
123
+ const field = err.field;
124
+ return typeof field === "string" ? field : undefined;
125
+ }
126
+ exports.getErrorField = getErrorField;
127
+ /**
128
+ * Extract error messages array from a validation error.
129
+ * Used for errors that carry multiple individual messages (e.g. ValidationError).
130
+ */
131
+ function getErrorMessages(err) {
132
+ if (!err || typeof err !== "object")
133
+ return undefined;
134
+ const messages = err.errorMessages;
135
+ if (!Array.isArray(messages))
136
+ return undefined;
137
+ return extractErrorMessages(messages);
138
+ }
139
+ exports.getErrorMessages = getErrorMessages;
140
+ /**
141
+ * Extract structured error properties for telemetry.
142
+ *
143
+ * @param err - The error object
144
+ * @returns Object with error properties suitable for telemetry
145
+ */
146
+ function extractErrorProperties(err) {
147
+ const errorClass = getErrorClass(err);
148
+ const message = err instanceof Error ? err.message : String(err);
149
+ const errorCode = getErrorCode(err);
150
+ const entity = getErrorEntity(err);
151
+ const field = getErrorField(err);
152
+ const errorMessages = getErrorMessages(err);
153
+ const result = {};
154
+ // eslint-disable-next-line camelcase
155
+ if (errorClass)
156
+ result.error_class = errorClass;
157
+ // eslint-disable-next-line camelcase
158
+ if (message)
159
+ result.error_message = normalizeErrorMessage(message);
160
+ // eslint-disable-next-line camelcase
161
+ if (errorCode)
162
+ result.error_code = errorCode;
163
+ if (entity)
164
+ result.entity = entity;
165
+ if (field)
166
+ result.field = field;
167
+ // eslint-disable-next-line camelcase
168
+ if (errorMessages && errorMessages.length > 0)
169
+ result.error_messages = errorMessages;
170
+ return result;
171
+ }
172
+ exports.extractErrorProperties = extractErrorProperties;
173
+ /**
174
+ * Extract an array of error messages from multiple errors, redacted and truncated.
175
+ *
176
+ * Used for validation errors where multiple issues may be present.
177
+ *
178
+ * @param errors - Array of errors (strings or Error objects)
179
+ * @param maxCount - Maximum number of error messages to include
180
+ * @returns Array of redacted, truncated error messages
181
+ */
182
+ function extractErrorMessages(errors, maxCount = exports.MAX_ERROR_MESSAGES) {
183
+ return errors
184
+ .slice(0, maxCount)
185
+ .map((err) => {
186
+ const message = err instanceof Error ? err.message : String(err);
187
+ return normalizeErrorMessage(message);
188
+ });
189
+ }
190
+ exports.extractErrorMessages = extractErrorMessages;
191
+ /**
192
+ * Check if an error is a config or validation error (a user error).
193
+ *
194
+ * Config and validation errors should be marked as user errors, not CLI bugs.
195
+ */
196
+ function isConfigOrValidationError(err) {
197
+ if (!err)
198
+ return false;
199
+ // ApsorcNamingError and anything with userError=true
200
+ if (err instanceof apsorc_parser_1.ApsorcNamingError)
201
+ return true;
202
+ if (typeof err === "object" && err.userError === true) {
203
+ return true;
204
+ }
205
+ // Check error message patterns
206
+ if (err instanceof Error) {
207
+ const message = err.message.toLowerCase();
208
+ // Common validation/config error patterns
209
+ if (message.includes("validation failed") ||
210
+ message.includes("lint error") ||
211
+ message.includes("configuration validation failed") ||
212
+ message.includes("invalid") ||
213
+ message.includes("does not reference an existing entity") ||
214
+ message.includes("entity found with empty name") ||
215
+ message.includes("failed to read or parse .apsorc")) {
216
+ return true;
217
+ }
218
+ }
219
+ return false;
220
+ }
221
+ exports.isConfigOrValidationError = isConfigOrValidationError;
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Constants for detecting internal (Apso team/system) CLI runs.
3
+ *
4
+ * Internal runs are explicitly marked so external anonymous users can be
5
+ * isolated in both PostHog and Sentry. This is separate from CI: CI is not
6
+ * always internal, and internal is not always CI.
7
+ */
8
+ /**
9
+ * GitHub repository owners that are considered internal.
10
+ * Any workflow in a repo owned by these orgs/users is marked internal.
11
+ */
12
+ export declare const INTERNAL_GITHUB_OWNERS: string[];
13
+ /**
14
+ * Email domains that are considered internal.
15
+ * Users with these domains are marked as internal.
16
+ */
17
+ export declare const INTERNAL_EMAIL_DOMAINS: string[];
18
+ /**
19
+ * Workspace slugs that are considered internal.
20
+ * Users in these workspaces are marked as internal.
21
+ */
22
+ export declare const INTERNAL_WORKSPACE_SLUGS: string[];
23
+ /**
24
+ * Workspace IDs that are considered internal.
25
+ * Users in these workspaces are marked as internal.
26
+ */
27
+ export declare const INTERNAL_WORKSPACE_IDS: string[];
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ /**
3
+ * Constants for detecting internal (Apso team/system) CLI runs.
4
+ *
5
+ * Internal runs are explicitly marked so external anonymous users can be
6
+ * isolated in both PostHog and Sentry. This is separate from CI: CI is not
7
+ * always internal, and internal is not always CI.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.INTERNAL_WORKSPACE_IDS = exports.INTERNAL_WORKSPACE_SLUGS = exports.INTERNAL_EMAIL_DOMAINS = exports.INTERNAL_GITHUB_OWNERS = void 0;
11
+ /**
12
+ * GitHub repository owners that are considered internal.
13
+ * Any workflow in a repo owned by these orgs/users is marked internal.
14
+ */
15
+ exports.INTERNAL_GITHUB_OWNERS = ["apsoai"];
16
+ /**
17
+ * Email domains that are considered internal.
18
+ * Users with these domains are marked as internal.
19
+ */
20
+ exports.INTERNAL_EMAIL_DOMAINS = ["apso.ai", "mavrictech.com"];
21
+ /**
22
+ * Workspace slugs that are considered internal.
23
+ * Users in these workspaces are marked as internal.
24
+ */
25
+ exports.INTERNAL_WORKSPACE_SLUGS = ["apso", "apso-team", "mavric"];
26
+ /**
27
+ * Workspace IDs that are considered internal.
28
+ * Users in these workspaces are marked as internal.
29
+ */
30
+ exports.INTERNAL_WORKSPACE_IDS = [
31
+ // Add specific workspace IDs here when known
32
+ ];
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Detection logic for internal (Apso team/system) CLI runs.
3
+ *
4
+ * Multiple detection methods ensure all internal runs are tagged, with any
5
+ * match marking the run as internal. The override env var APSO_INTERNAL=0
6
+ * forces false for testing external behavior internally.
7
+ */
8
+ export type InternalReason = "env" | "github_owner" | "config" | "account" | "workspace";
9
+ export interface InternalDetectionResult {
10
+ internal: boolean;
11
+ reason?: InternalReason;
12
+ }
13
+ /**
14
+ * Detect if this CLI run should be marked as internal.
15
+ *
16
+ * Detection methods, in order of precedence:
17
+ * 1. Explicit env var APSO_INTERNAL (1/true = internal, 0 = force false override)
18
+ * 2. GitHub Actions auto-detection (GITHUB_ACTIONS=true + owner in INTERNAL_GITHUB_OWNERS)
19
+ * 3. Config flag: `apso config set internal true`
20
+ * 4. Account-based: authenticated user email domain or workspace
21
+ *
22
+ * @param opts - Detection context
23
+ * @returns Object with internal boolean and reason
24
+ */
25
+ export declare function detectInternal(opts: {
26
+ configInternal?: boolean;
27
+ userEmail?: string;
28
+ workspaceSlug?: string;
29
+ workspaceId?: string;
30
+ }): InternalDetectionResult;
31
+ /**
32
+ * Extract email domain from an email address (without sending the full email).
33
+ *
34
+ * @param email - Email address
35
+ * @returns Domain part of the email (e.g., "apso.ai")
36
+ */
37
+ export declare function getEmailDomain(email: string): string | undefined;
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ /**
3
+ * Detection logic for internal (Apso team/system) CLI runs.
4
+ *
5
+ * Multiple detection methods ensure all internal runs are tagged, with any
6
+ * match marking the run as internal. The override env var APSO_INTERNAL=0
7
+ * forces false for testing external behavior internally.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.getEmailDomain = exports.detectInternal = void 0;
11
+ const internal_constants_1 = require("./internal-constants");
12
+ /**
13
+ * Detect if this CLI run should be marked as internal.
14
+ *
15
+ * Detection methods, in order of precedence:
16
+ * 1. Explicit env var APSO_INTERNAL (1/true = internal, 0 = force false override)
17
+ * 2. GitHub Actions auto-detection (GITHUB_ACTIONS=true + owner in INTERNAL_GITHUB_OWNERS)
18
+ * 3. Config flag: `apso config set internal true`
19
+ * 4. Account-based: authenticated user email domain or workspace
20
+ *
21
+ * @param opts - Detection context
22
+ * @returns Object with internal boolean and reason
23
+ */
24
+ function detectInternal(opts) {
25
+ var _a, _b;
26
+ // 1. Explicit env var (with override)
27
+ const envVar = process.env.APSO_INTERNAL;
28
+ if (envVar === "0" || envVar === "false") {
29
+ // Force false - for testing external behavior internally
30
+ return { internal: false };
31
+ }
32
+ if (envVar === "1" || envVar === "true") {
33
+ return { internal: true, reason: "env" };
34
+ }
35
+ // 2. GitHub Actions auto-detection
36
+ if (process.env.GITHUB_ACTIONS === "true") {
37
+ const repoOwner = process.env.GITHUB_REPOSITORY_OWNER ||
38
+ ((_a = process.env.GITHUB_REPOSITORY) === null || _a === void 0 ? void 0 : _a.split("/")[0]);
39
+ if (repoOwner &&
40
+ internal_constants_1.INTERNAL_GITHUB_OWNERS.some((owner) => owner.toLowerCase() === repoOwner.toLowerCase())) {
41
+ return { internal: true, reason: "github_owner" };
42
+ }
43
+ }
44
+ // 3. Config flag: apso config set internal true
45
+ if (opts.configInternal === true) {
46
+ return { internal: true, reason: "config" };
47
+ }
48
+ // 4. Account-based: email domain
49
+ if (opts.userEmail) {
50
+ const domain = (_b = opts.userEmail.split("@")[1]) === null || _b === void 0 ? void 0 : _b.toLowerCase();
51
+ if (domain && internal_constants_1.INTERNAL_EMAIL_DOMAINS.includes(domain)) {
52
+ return { internal: true, reason: "account" };
53
+ }
54
+ }
55
+ // 4. Account-based: workspace slug or ID
56
+ if (opts.workspaceSlug) {
57
+ const slug = opts.workspaceSlug.toLowerCase();
58
+ if (internal_constants_1.INTERNAL_WORKSPACE_SLUGS.includes(slug)) {
59
+ return { internal: true, reason: "workspace" };
60
+ }
61
+ }
62
+ if (opts.workspaceId && internal_constants_1.INTERNAL_WORKSPACE_IDS.includes(opts.workspaceId)) {
63
+ return { internal: true, reason: "workspace" };
64
+ }
65
+ return { internal: false };
66
+ }
67
+ exports.detectInternal = detectInternal;
68
+ /**
69
+ * Extract email domain from an email address (without sending the full email).
70
+ *
71
+ * @param email - Email address
72
+ * @returns Domain part of the email (e.g., "apso.ai")
73
+ */
74
+ function getEmailDomain(email) {
75
+ var _a;
76
+ return (_a = email.split("@")[1]) === null || _a === void 0 ? void 0 : _a.toLowerCase();
77
+ }
78
+ exports.getEmailDomain = getEmailDomain;
@@ -28,6 +28,17 @@ export declare function markFirstRunNoticeShown(): void;
28
28
  export declare function track(event: string, properties?: Record<string, unknown>): void;
29
29
  /** Report an exception to Sentry. No-op when disabled. */
30
30
  export declare function captureException(err: unknown, context?: Record<string, unknown>): void;
31
+ /**
32
+ * Capture an exception event in PostHog with structured error properties.
33
+ *
34
+ * PostHog's posthog-node SDK (v5.21.2+) doesn't have a direct captureException
35
+ * method, so we send an $exception event with $exception_list in the standard
36
+ * format: https://posthog.com/docs/data/exceptions
37
+ *
38
+ * @param err - The error to capture
39
+ * @param context - Additional context properties (command, etc.)
40
+ */
41
+ export declare function capturePostHogException(err: unknown, context?: Record<string, unknown>): void;
31
42
  /** Milliseconds since the process (CLI invocation) started. */
32
43
  export declare function elapsedMs(): number;
33
44
  /** Flush + close both clients. Call before the process exits. */