@terreno/api 0.22.2 → 0.23.1

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.
package/dist/api.test.js CHANGED
@@ -2639,15 +2639,19 @@ var transformers_1 = require("./transformers");
2639
2639
  });
2640
2640
  }); });
2641
2641
  (0, bun_test_1.it)("handles doc timestamp stored as ISO string", function () { return __awaiter(void 0, void 0, void 0, function () {
2642
- var res;
2642
+ var ifUnmodifiedSince, res;
2643
2643
  return __generator(this, function (_a) {
2644
2644
  switch (_a.label) {
2645
2645
  case 0: return [4 /*yield*/, tests_1.FoodModel.collection.updateOne({ _id: spinach._id }, { $set: { updated: "2025-06-15T12:00:00.000Z" } })];
2646
2646
  case 1:
2647
2647
  _a.sent();
2648
+ ifUnmodifiedSince = luxon_1.DateTime.fromISO("2025-06-15T11:00:00.000Z").toHTTP();
2649
+ if (!ifUnmodifiedSince) {
2650
+ throw new Error("Expected valid HTTP date");
2651
+ }
2648
2652
  return [4 /*yield*/, agent
2649
2653
  .patch("/food/".concat(spinach._id))
2650
- .set("If-Unmodified-Since", luxon_1.DateTime.fromISO("2025-06-15T11:00:00.000Z").toHTTP())
2654
+ .set("If-Unmodified-Since", ifUnmodifiedSince)
2651
2655
  .send({ name: "String Timestamp" })
2652
2656
  .expect(409)];
2653
2657
  case 2:
package/dist/auth.test.js CHANGED
@@ -1702,3 +1702,55 @@ var decodeTokenPayload = function (token) {
1702
1702
  });
1703
1703
  }); });
1704
1704
  });
1705
+ (0, bun_test_1.describe)("PATCH /me route edge cases", function () {
1706
+ var app;
1707
+ var agent;
1708
+ (0, bun_test_1.beforeEach)(function () { return __awaiter(void 0, void 0, void 0, function () {
1709
+ return __generator(this, function (_a) {
1710
+ switch (_a.label) {
1711
+ case 0:
1712
+ (0, bun_test_1.setSystemTime)();
1713
+ return [4 /*yield*/, (0, tests_1.setupTestData)()];
1714
+ case 1:
1715
+ _a.sent();
1716
+ app = new terrenoApp_1.TerrenoApp({
1717
+ configureApp: function () { },
1718
+ skipListen: true,
1719
+ userModel: tests_1.UserModel,
1720
+ }).build();
1721
+ agent = supertest_1.default.agent(app);
1722
+ return [2 /*return*/];
1723
+ }
1724
+ });
1725
+ }); });
1726
+ (0, bun_test_1.afterEach)(function () {
1727
+ (0, bun_test_1.setSystemTime)();
1728
+ });
1729
+ (0, bun_test_1.it)("returns 404 for PATCH /me when authenticated user is deleted from DB", function () { return __awaiter(void 0, void 0, void 0, function () {
1730
+ var loginRes, _a, token, userId, freshAgent, res;
1731
+ return __generator(this, function (_b) {
1732
+ switch (_b.label) {
1733
+ case 0: return [4 /*yield*/, agent
1734
+ .post("/auth/login")
1735
+ .send({ email: "notAdmin@example.com", password: "password" })
1736
+ .expect(200)];
1737
+ case 1:
1738
+ loginRes = _b.sent();
1739
+ _a = loginRes.body.data, token = _a.token, userId = _a.userId;
1740
+ return [4 /*yield*/, tests_1.UserModel.deleteOne({ _id: userId })];
1741
+ case 2:
1742
+ _b.sent();
1743
+ freshAgent = supertest_1.default.agent(app);
1744
+ return [4 /*yield*/, freshAgent
1745
+ .patch("/auth/me")
1746
+ .set("authorization", "Bearer ".concat(token))
1747
+ .send({ name: "Updated" })];
1748
+ case 3:
1749
+ res = _b.sent();
1750
+ // Without user in DB, should get 401 or 404
1751
+ (0, bun_test_1.expect)([401, 404]).toContain(res.status);
1752
+ return [2 /*return*/];
1753
+ }
1754
+ });
1755
+ }); });
1756
+ });
@@ -7,8 +7,11 @@
7
7
  */
8
8
  import { type Application } from "express";
9
9
  import type { User } from "./auth";
10
+ import type { PopulatePath } from "./populate";
10
11
  import type { TerrenoPlugin } from "./terrenoPlugin";
11
12
  import type { ConsentFormDocument } from "./types/consentForm";
13
+ /** Shared populate config for consent response list/read endpoints. */
14
+ export declare const consentResponsePopulatePaths: PopulatePath[];
12
15
  export interface ConsentAppOptions {
13
16
  auditTrail?: boolean;
14
17
  aiConfig?: {
@@ -54,7 +54,7 @@ var __values = (this && this.__values) || function(o) {
54
54
  throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
55
55
  };
56
56
  Object.defineProperty(exports, "__esModule", { value: true });
57
- exports.ConsentApp = void 0;
57
+ exports.ConsentApp = exports.consentResponsePopulatePaths = void 0;
58
58
  var express_1 = require("express");
59
59
  var luxon_1 = require("luxon");
60
60
  var api_1 = require("./api");
@@ -64,6 +64,17 @@ var logger_1 = require("./logger");
64
64
  var consentForm_1 = require("./models/consentForm");
65
65
  var consentResponse_1 = require("./models/consentResponse");
66
66
  var permissions_1 = require("./permissions");
67
+ /** Shared populate config for consent response list/read endpoints. */
68
+ exports.consentResponsePopulatePaths = [
69
+ {
70
+ fields: ["title", "slug", "version", "type"],
71
+ path: "consentFormId",
72
+ },
73
+ {
74
+ fields: ["name", "email"],
75
+ path: "userId",
76
+ },
77
+ ];
67
78
  var requireAdmin = function (user) {
68
79
  if (!(user === null || user === void 0 ? void 0 : user.admin)) {
69
80
  throw new errors_1.APIError({ status: 403, title: "Admin access required" });
@@ -217,12 +228,7 @@ var ConsentApp = /** @class */ (function () {
217
228
  read: [permissions_1.Permissions.IsAdmin],
218
229
  update: [],
219
230
  },
220
- populatePaths: [
221
- {
222
- fields: ["title", "slug", "version", "type"],
223
- path: "consentFormId",
224
- },
225
- ],
231
+ populatePaths: exports.consentResponsePopulatePaths,
226
232
  }));
227
233
  // User-facing consent endpoints
228
234
  var router = (0, express_1.Router)();
@@ -331,6 +331,41 @@ var buildApp = function (consentAppOptions) {
331
331
  }
332
332
  });
333
333
  }); });
334
+ (0, bun_test_1.it)("populates consentFormId and userId on read", function () { return __awaiter(void 0, void 0, void 0, function () {
335
+ var form, response, res;
336
+ return __generator(this, function (_a) {
337
+ switch (_a.label) {
338
+ case 0: return [4 /*yield*/, consentForm_1.ConsentForm.create({
339
+ active: true,
340
+ content: new Map([["en", "# Terms"]]),
341
+ order: 1,
342
+ slug: "terms-populated",
343
+ title: "Terms Populated",
344
+ type: "terms",
345
+ version: 1,
346
+ })];
347
+ case 1:
348
+ form = _a.sent();
349
+ return [4 /*yield*/, consentResponse_1.ConsentResponse.create({
350
+ agreed: true,
351
+ agreedAt: new Date(),
352
+ consentFormId: form._id,
353
+ formVersionSnapshot: 1,
354
+ locale: "en",
355
+ userId: notAdmin._id,
356
+ })];
357
+ case 2:
358
+ response = _a.sent();
359
+ return [4 /*yield*/, adminAgent.get("/consent-responses/".concat(response._id)).expect(200)];
360
+ case 3:
361
+ res = _a.sent();
362
+ (0, bun_test_1.expect)(res.body.data.consentFormId.title).toBe("Terms Populated");
363
+ (0, bun_test_1.expect)(res.body.data.userId.email).toBe(notAdmin.email);
364
+ (0, bun_test_1.expect)(res.body.data.userId.name).toBe(notAdmin.name);
365
+ return [2 /*return*/];
366
+ }
367
+ });
368
+ }); });
334
369
  (0, bun_test_1.it)("blocks non-admins from listing responses", function () { return __awaiter(void 0, void 0, void 0, function () {
335
370
  return __generator(this, function (_a) {
336
371
  switch (_a.label) {
@@ -108,7 +108,6 @@ var __read = (this && this.__read) || function (o, n) {
108
108
  };
109
109
  var _a;
110
110
  Object.defineProperty(exports, "__esModule", { value: true });
111
- // biome-ignore-all lint/suspicious/noExplicitAny: test model typing
112
111
  var bun_test_1 = require("bun:test");
113
112
  var mongoose_1 = __importStar(require("mongoose"));
114
113
  var config_1 = require("./config");
@@ -340,7 +339,7 @@ var setupLoader = function () {
340
339
  });
341
340
  }); });
342
341
  (0, bun_test_1.it)("refreshFromDoc logs a warning and does not throw when the model query fails", function () { return __awaiter(void 0, void 0, void 0, function () {
343
- var doc, originalFind;
342
+ var doc, findSpy;
344
343
  return __generator(this, function (_a) {
345
344
  switch (_a.label) {
346
345
  case 0:
@@ -351,17 +350,16 @@ var setupLoader = function () {
351
350
  _a.sent();
352
351
  // Pre-set cache to verify it is NOT overwritten when the hook errors
353
352
  config_1.Config.setCachedEnv({ TERRENO_PLUGIN_KEY: "cached" });
354
- originalFind = TestEnvConfig.find;
355
- TestEnvConfig.find = function () {
353
+ findSpy = (0, bun_test_1.spyOn)(TestEnvConfig, "find").mockImplementation(function () {
356
354
  throw new Error("Simulated DB error");
357
- };
355
+ });
358
356
  // Trigger the post-findOneAndUpdate hook → refreshFromDoc → findOneOrNoneFor → throws
359
357
  return [4 /*yield*/, TestEnvConfig.findOneAndUpdate({ _id: doc._id }, { $set: { __v: 2 } })];
360
358
  case 2:
361
359
  // Trigger the post-findOneAndUpdate hook → refreshFromDoc → findOneOrNoneFor → throws
362
360
  _a.sent();
363
361
  // Restore immediately
364
- TestEnvConfig.find = originalFind;
362
+ findSpy.mockRestore();
365
363
  // The catch block should have swallowed the error; cache keeps old value
366
364
  (0, bun_test_1.expect)(config_1.Config.get("TERRENO_PLUGIN_KEY")).toBe("cached");
367
365
  return [2 /*return*/];
@@ -99,7 +99,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
99
99
  return (mod && mod.__esModule) ? mod : { "default": mod };
100
100
  };
101
101
  Object.defineProperty(exports, "__esModule", { value: true });
102
- // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
103
102
  var bun_test_1 = require("bun:test");
104
103
  var Sentry = __importStar(require("@sentry/bun"));
105
104
  var axios_1 = __importDefault(require("axios"));
@@ -108,7 +107,9 @@ var zoomNotifier_1 = require("./zoomNotifier");
108
107
  var mockAxiosPost;
109
108
  var ORIGINAL_ENV = process.env;
110
109
  (0, bun_test_1.beforeEach)(function () {
111
- mockAxiosPost = (0, bun_test_1.spyOn)(axios_1.default, "post").mockResolvedValue({ status: 200 });
110
+ mockAxiosPost = (0, bun_test_1.spyOn)(axios_1.default, "post").mockResolvedValue({
111
+ status: 200,
112
+ });
112
113
  process.env = __assign({}, ORIGINAL_ENV);
113
114
  process.env.ZOOM_CHAT_WEBHOOKS = undefined;
114
115
  Sentry.captureException.mockClear();
@@ -3,6 +3,51 @@ export interface ScriptResult {
3
3
  success: boolean;
4
4
  results: string[];
5
5
  }
6
+ /** A single parsed argument value. Repeated flags collapse into a string array. */
7
+ export type ScriptArgValue = string | number | boolean | string[];
8
+ /**
9
+ * Optional declaration for a single script argument. Declarations are purely
10
+ * advisory: they drive validation, type coercion, default values, and help text
11
+ * but a script can still read any argument the caller supplied. This keeps
12
+ * argument handling flexible — declare the args you care about, ignore the rest.
13
+ */
14
+ export interface ScriptArgDef {
15
+ /** Canonical name (used as `--name` on the CLI and as the key in the args map). */
16
+ name: string;
17
+ /** Human-readable description shown in CLI help and the admin UI. */
18
+ description: string;
19
+ /** Type used for coercion and validation. Defaults to "string". */
20
+ type?: "string" | "number" | "boolean";
21
+ /** When true, parsing fails if the argument is missing. */
22
+ required?: boolean;
23
+ /** Default applied when the argument is not provided. */
24
+ default?: ScriptArgValue;
25
+ /** Alternate names accepted on the CLI (e.g. ["l"] enables `-l`). */
26
+ aliases?: string[];
27
+ /** Example value shown in help text. */
28
+ example?: string;
29
+ }
30
+ /**
31
+ * Typed, ergonomic accessor over the parsed arguments passed to a script. Scripts
32
+ * read values via the typed getters; `raw` and `positional` expose everything for
33
+ * advanced cases.
34
+ */
35
+ export interface ScriptArgs {
36
+ /** All named values keyed by canonical name. */
37
+ raw: Record<string, ScriptArgValue>;
38
+ /** Positional (non-flag) arguments, in order. */
39
+ positional: string[];
40
+ /** Whether a named argument was supplied (or has a default). */
41
+ has: (name: string) => boolean;
42
+ /** Read a string value (coerces numbers/booleans; first element of arrays). */
43
+ getString: (name: string, fallback?: string) => string | undefined;
44
+ /** Read a numeric value (coerces strings; returns fallback when missing/NaN). */
45
+ getNumber: (name: string, fallback?: number) => number | undefined;
46
+ /** Read a boolean value ("true"/"1"/"yes"/"on" are truthy). */
47
+ getBoolean: (name: string, fallback?: boolean) => boolean;
48
+ /** Read a string array (single values become a one-element array). */
49
+ getStringArray: (name: string) => string[];
50
+ }
6
51
  export interface ScriptContext {
7
52
  /** Check if the task has been cancelled. Throws TaskCancelledError if so. */
8
53
  checkCancellation: () => Promise<void>;
@@ -10,8 +55,40 @@ export interface ScriptContext {
10
55
  addLog: (level: "info" | "warn" | "error", message: string) => Promise<void>;
11
56
  /** Update progress on the task. */
12
57
  updateProgress: (percentage: number, stage?: string, message?: string) => Promise<void>;
58
+ /** Arguments supplied to this run (from the CLI, HTTP body, or admin UI). */
59
+ args: ScriptArgs;
13
60
  }
14
61
  export type ScriptRunner = (wetRun: boolean, ctx?: ScriptContext) => Promise<ScriptResult>;
62
+ /**
63
+ * Build a {@link ScriptArgs} accessor from a raw values map and optional declarations.
64
+ * Applies declared defaults, coerces declared types, and validates required args.
65
+ * Returns the accessor plus any validation errors (callers decide how to surface them).
66
+ */
67
+ export declare const createScriptArgs: ({ values, positional, defs, }: {
68
+ values: Record<string, ScriptArgValue>;
69
+ positional?: string[];
70
+ defs?: ScriptArgDef[];
71
+ }) => {
72
+ args: ScriptArgs;
73
+ errors: string[];
74
+ };
75
+ /**
76
+ * Parse CLI-style tokens into a {@link ScriptArgs} accessor. Supports a flexible set
77
+ * of conventions so callers and scripts do not need to agree on a rigid format:
78
+ *
79
+ * - `--name=value` and `--name value`
80
+ * - `--flag` (boolean true) and `--no-flag` (boolean false)
81
+ * - short aliases `-x` (treated like `--x`)
82
+ * - repeated flags collapse into a string array
83
+ * - bare tokens become positional arguments
84
+ *
85
+ * When {@link ScriptArgDef declarations} are supplied, values are coerced to the
86
+ * declared type, defaults are applied, and required args are validated.
87
+ */
88
+ export declare const parseScriptArgs: (tokens: string[], defs?: ScriptArgDef[]) => {
89
+ args: ScriptArgs;
90
+ errors: string[];
91
+ };
15
92
  export declare class TaskCancelledError extends Error {
16
93
  constructor(taskId: string);
17
94
  }
@@ -14,6 +14,17 @@ var __extends = (this && this.__extends) || (function () {
14
14
  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
15
  };
16
16
  })();
17
+ var __assign = (this && this.__assign) || function () {
18
+ __assign = Object.assign || function(t) {
19
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
20
+ s = arguments[i];
21
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
22
+ t[p] = s[p];
23
+ }
24
+ return t;
25
+ };
26
+ return __assign.apply(this, arguments);
27
+ };
17
28
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
18
29
  if (k2 === undefined) k2 = k;
19
30
  var desc = Object.getOwnPropertyDescriptor(m, k);
@@ -83,11 +94,257 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
83
94
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
84
95
  }
85
96
  };
97
+ var __values = (this && this.__values) || function(o) {
98
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
99
+ if (m) return m.call(o);
100
+ if (o && typeof o.length === "number") return {
101
+ next: function () {
102
+ if (o && i >= o.length) o = void 0;
103
+ return { value: o && o[i++], done: !o };
104
+ }
105
+ };
106
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
107
+ };
108
+ var __read = (this && this.__read) || function (o, n) {
109
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
110
+ if (!m) return o;
111
+ var i = m.call(o), r, ar = [], e;
112
+ try {
113
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
114
+ }
115
+ catch (error) { e = { error: error }; }
116
+ finally {
117
+ try {
118
+ if (r && !r.done && (m = i["return"])) m.call(i);
119
+ }
120
+ finally { if (e) throw e.error; }
121
+ }
122
+ return ar;
123
+ };
124
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
125
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
126
+ if (ar || !(i in from)) {
127
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
128
+ ar[i] = from[i];
129
+ }
130
+ }
131
+ return to.concat(ar || Array.prototype.slice.call(from));
132
+ };
86
133
  Object.defineProperty(exports, "__esModule", { value: true });
87
- exports.BackgroundTask = exports.TaskCancelledError = void 0;
134
+ exports.BackgroundTask = exports.TaskCancelledError = exports.parseScriptArgs = exports.createScriptArgs = void 0;
88
135
  var luxon_1 = require("luxon");
89
136
  var mongoose_1 = __importStar(require("mongoose"));
90
137
  var plugins_1 = require("./plugins");
138
+ var coerceArgValue = function (value, type) {
139
+ if (type === "number") {
140
+ var num = typeof value === "number" ? value : Number(Array.isArray(value) ? value[0] : value);
141
+ if (Number.isNaN(num)) {
142
+ return { error: "expected a number but received \"".concat(String(value), "\""), value: value };
143
+ }
144
+ return { value: num };
145
+ }
146
+ if (type === "boolean") {
147
+ if (typeof value === "boolean") {
148
+ return { value: value };
149
+ }
150
+ var normalized = String(Array.isArray(value) ? value[0] : value).toLowerCase();
151
+ if (["true", "1", "yes", "on"].includes(normalized)) {
152
+ return { value: true };
153
+ }
154
+ if (["false", "0", "no", "off"].includes(normalized)) {
155
+ return { value: false };
156
+ }
157
+ return { error: "expected a boolean but received \"".concat(String(value), "\""), value: value };
158
+ }
159
+ return { value: value };
160
+ };
161
+ var toStringValue = function (value) {
162
+ if (value === undefined) {
163
+ return undefined;
164
+ }
165
+ if (Array.isArray(value)) {
166
+ return value[0];
167
+ }
168
+ return String(value);
169
+ };
170
+ /**
171
+ * Build a {@link ScriptArgs} accessor from a raw values map and optional declarations.
172
+ * Applies declared defaults, coerces declared types, and validates required args.
173
+ * Returns the accessor plus any validation errors (callers decide how to surface them).
174
+ */
175
+ var createScriptArgs = function (_a) {
176
+ var e_1, _b;
177
+ var values = _a.values, _c = _a.positional, positional = _c === void 0 ? [] : _c, _d = _a.defs, defs = _d === void 0 ? [] : _d;
178
+ var errors = [];
179
+ var raw = __assign({}, values);
180
+ try {
181
+ for (var defs_1 = __values(defs), defs_1_1 = defs_1.next(); !defs_1_1.done; defs_1_1 = defs_1.next()) {
182
+ var def = defs_1_1.value;
183
+ if (raw[def.name] === undefined) {
184
+ if (def.default !== undefined) {
185
+ raw[def.name] = def.default;
186
+ }
187
+ else if (def.required) {
188
+ errors.push("Missing required argument: --".concat(def.name, " (").concat(def.description, ")"));
189
+ }
190
+ continue;
191
+ }
192
+ var coerced = coerceArgValue(raw[def.name], def.type);
193
+ if (coerced.error) {
194
+ errors.push("Invalid argument --".concat(def.name, ": ").concat(coerced.error));
195
+ continue;
196
+ }
197
+ raw[def.name] = coerced.value;
198
+ }
199
+ }
200
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
201
+ finally {
202
+ try {
203
+ if (defs_1_1 && !defs_1_1.done && (_b = defs_1.return)) _b.call(defs_1);
204
+ }
205
+ finally { if (e_1) throw e_1.error; }
206
+ }
207
+ var args = {
208
+ getBoolean: function (name, fallback) {
209
+ var _a;
210
+ if (fallback === void 0) { fallback = false; }
211
+ var value = raw[name];
212
+ if (value === undefined) {
213
+ return fallback;
214
+ }
215
+ if (typeof value === "boolean") {
216
+ return value;
217
+ }
218
+ var normalized = (_a = toStringValue(value)) === null || _a === void 0 ? void 0 : _a.toLowerCase();
219
+ return normalized !== undefined && ["true", "1", "yes", "on"].includes(normalized);
220
+ },
221
+ getNumber: function (name, fallback) {
222
+ var value = raw[name];
223
+ if (value === undefined) {
224
+ return fallback;
225
+ }
226
+ var num = typeof value === "number" ? value : Number(toStringValue(value));
227
+ return Number.isNaN(num) ? fallback : num;
228
+ },
229
+ getString: function (name, fallback) { var _a; return (_a = toStringValue(raw[name])) !== null && _a !== void 0 ? _a : fallback; },
230
+ getStringArray: function (name) {
231
+ var value = raw[name];
232
+ if (value === undefined) {
233
+ return [];
234
+ }
235
+ if (Array.isArray(value)) {
236
+ return value;
237
+ }
238
+ return [String(value)];
239
+ },
240
+ has: function (name) { return raw[name] !== undefined; },
241
+ positional: positional,
242
+ raw: raw,
243
+ };
244
+ return { args: args, errors: errors };
245
+ };
246
+ exports.createScriptArgs = createScriptArgs;
247
+ /**
248
+ * Parse CLI-style tokens into a {@link ScriptArgs} accessor. Supports a flexible set
249
+ * of conventions so callers and scripts do not need to agree on a rigid format:
250
+ *
251
+ * - `--name=value` and `--name value`
252
+ * - `--flag` (boolean true) and `--no-flag` (boolean false)
253
+ * - short aliases `-x` (treated like `--x`)
254
+ * - repeated flags collapse into a string array
255
+ * - bare tokens become positional arguments
256
+ *
257
+ * When {@link ScriptArgDef declarations} are supplied, values are coerced to the
258
+ * declared type, defaults are applied, and required args are validated.
259
+ */
260
+ var parseScriptArgs = function (tokens, defs) {
261
+ var e_2, _a, e_3, _b;
262
+ var _c, _d, _e;
263
+ if (defs === void 0) { defs = []; }
264
+ var aliasToName = new Map();
265
+ var defByName = new Map();
266
+ try {
267
+ for (var defs_2 = __values(defs), defs_2_1 = defs_2.next(); !defs_2_1.done; defs_2_1 = defs_2.next()) {
268
+ var def = defs_2_1.value;
269
+ defByName.set(def.name, def);
270
+ try {
271
+ for (var _f = (e_3 = void 0, __values((_c = def.aliases) !== null && _c !== void 0 ? _c : [])), _g = _f.next(); !_g.done; _g = _f.next()) {
272
+ var alias = _g.value;
273
+ aliasToName.set(alias, def.name);
274
+ }
275
+ }
276
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
277
+ finally {
278
+ try {
279
+ if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
280
+ }
281
+ finally { if (e_3) throw e_3.error; }
282
+ }
283
+ }
284
+ }
285
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
286
+ finally {
287
+ try {
288
+ if (defs_2_1 && !defs_2_1.done && (_a = defs_2.return)) _a.call(defs_2);
289
+ }
290
+ finally { if (e_2) throw e_2.error; }
291
+ }
292
+ var values = {};
293
+ var positional = [];
294
+ var missingValueErrors = [];
295
+ var assign = function (key, value) {
296
+ var _a;
297
+ var name = (_a = aliasToName.get(key)) !== null && _a !== void 0 ? _a : key;
298
+ var existing = values[name];
299
+ if (existing === undefined) {
300
+ values[name] = value;
301
+ return;
302
+ }
303
+ // Repeated flag: collapse into an array of strings.
304
+ var asArray = Array.isArray(existing) ? existing : [String(existing)];
305
+ values[name] = __spreadArray(__spreadArray([], __read(asArray), false), [String(value)], false);
306
+ };
307
+ for (var i = 0; i < tokens.length; i++) {
308
+ var token = tokens[i];
309
+ if (!token.startsWith("-") || token === "-") {
310
+ positional.push(token);
311
+ continue;
312
+ }
313
+ var flag = token.replace(/^-+/, "");
314
+ if (flag.startsWith("no-") && !flag.includes("=")) {
315
+ assign(flag.slice(3), false);
316
+ continue;
317
+ }
318
+ var eqIndex = flag.indexOf("=");
319
+ if (eqIndex !== -1) {
320
+ assign(flag.slice(0, eqIndex), flag.slice(eqIndex + 1));
321
+ continue;
322
+ }
323
+ var canonical = (_d = aliasToName.get(flag)) !== null && _d !== void 0 ? _d : flag;
324
+ var def = defByName.get(canonical);
325
+ var next = tokens[i + 1];
326
+ var nextIsValue = next !== undefined && (next === "-" || !next.startsWith("-"));
327
+ if ((def === null || def === void 0 ? void 0 : def.type) === "boolean") {
328
+ assign(flag, true);
329
+ continue;
330
+ }
331
+ if (!nextIsValue) {
332
+ // A declared string/number flag was given without a value. Record an error
333
+ // instead of silently storing `true` (which would coerce to 1 / "true").
334
+ if (def) {
335
+ missingValueErrors.push("Argument --".concat(canonical, " expects a ").concat((_e = def.type) !== null && _e !== void 0 ? _e : "string", " value"));
336
+ continue;
337
+ }
338
+ assign(flag, true);
339
+ continue;
340
+ }
341
+ assign(flag, next);
342
+ i++;
343
+ }
344
+ var _h = (0, exports.createScriptArgs)({ defs: defs, positional: positional, values: values }), args = _h.args, errors = _h.errors;
345
+ return { args: args, errors: __spreadArray(__spreadArray([], __read(missingValueErrors), false), __read(errors), false) };
346
+ };
347
+ exports.parseScriptArgs = parseScriptArgs;
91
348
  var TaskCancelledError = /** @class */ (function (_super) {
92
349
  __extends(TaskCancelledError, _super);
93
350
  function TaskCancelledError(taskId) {
@@ -0,0 +1 @@
1
+ export {};