@voxgig/station 0.0.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.
Files changed (67) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +88 -0
  3. package/dist/src/Station.d.ts +238 -0
  4. package/dist/src/Station.js +1213 -0
  5. package/dist/src/Station.js.map +1 -0
  6. package/dist/src/adapter.d.ts +9 -0
  7. package/dist/src/adapter.js +171 -0
  8. package/dist/src/adapter.js.map +1 -0
  9. package/dist/src/config-shape.d.ts +1 -0
  10. package/dist/src/config-shape.js +329 -0
  11. package/dist/src/config-shape.js.map +1 -0
  12. package/dist/src/descriptor.d.ts +8 -0
  13. package/dist/src/descriptor.js +170 -0
  14. package/dist/src/descriptor.js.map +1 -0
  15. package/dist/src/error.d.ts +8 -0
  16. package/dist/src/error.js +60 -0
  17. package/dist/src/error.js.map +1 -0
  18. package/dist/src/events.d.ts +15 -0
  19. package/dist/src/events.js +46 -0
  20. package/dist/src/events.js.map +1 -0
  21. package/dist/src/factory.d.ts +24 -0
  22. package/dist/src/factory.js +79 -0
  23. package/dist/src/factory.js.map +1 -0
  24. package/dist/src/feature.d.ts +106 -0
  25. package/dist/src/feature.js +324 -0
  26. package/dist/src/feature.js.map +1 -0
  27. package/dist/src/index.browser.d.ts +14 -0
  28. package/dist/src/index.browser.js +64 -0
  29. package/dist/src/index.browser.js.map +1 -0
  30. package/dist/src/index.d.ts +14 -0
  31. package/dist/src/index.js +56 -0
  32. package/dist/src/index.js.map +1 -0
  33. package/dist/src/loader.d.ts +45 -0
  34. package/dist/src/loader.js +181 -0
  35. package/dist/src/loader.js.map +1 -0
  36. package/dist/src/profile.d.ts +6 -0
  37. package/dist/src/profile.js +77 -0
  38. package/dist/src/profile.js.map +1 -0
  39. package/dist/src/profilecore.d.ts +10 -0
  40. package/dist/src/profilecore.js +180 -0
  41. package/dist/src/profilecore.js.map +1 -0
  42. package/dist/src/secrets.d.ts +12 -0
  43. package/dist/src/secrets.js +93 -0
  44. package/dist/src/secrets.js.map +1 -0
  45. package/dist/src/shape.d.ts +42 -0
  46. package/dist/src/shape.js +444 -0
  47. package/dist/src/shape.js.map +1 -0
  48. package/dist/src/types.d.ts +138 -0
  49. package/dist/src/types.js +5 -0
  50. package/dist/src/types.js.map +1 -0
  51. package/package.json +60 -0
  52. package/src/Station.ts +1310 -0
  53. package/src/adapter.ts +183 -0
  54. package/src/config-shape.ts +326 -0
  55. package/src/descriptor.ts +179 -0
  56. package/src/error.ts +64 -0
  57. package/src/events.ts +45 -0
  58. package/src/factory.ts +93 -0
  59. package/src/feature.ts +321 -0
  60. package/src/index.browser.ts +56 -0
  61. package/src/index.ts +50 -0
  62. package/src/loader.ts +188 -0
  63. package/src/profile.ts +67 -0
  64. package/src/profilecore.ts +201 -0
  65. package/src/secrets.ts +96 -0
  66. package/src/shape.ts +435 -0
  67. package/src/types.ts +185 -0
@@ -0,0 +1,1213 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Station = void 0;
4
+ exports.setConfigFileIO = setConfigFileIO;
5
+ exports.instanceRef = instanceRef;
6
+ exports.checkInstanceName = checkInstanceName;
7
+ exports.checkInstanceTag = checkInstanceTag;
8
+ const adapter_1 = require("./adapter");
9
+ const error_1 = require("./error");
10
+ const events_1 = require("./events");
11
+ const descriptor_1 = require("./descriptor");
12
+ const profilecore_1 = require("./profilecore");
13
+ const factory_1 = require("./factory");
14
+ const loader_1 = require("./loader");
15
+ const feature_1 = require("./feature");
16
+ const shape_1 = require("./shape");
17
+ const secrets_1 = require("./secrets");
18
+ let configfileio = null;
19
+ function setConfigFileIO(io) {
20
+ configfileio = io;
21
+ }
22
+ /** §6.1: `as` IS A TAG, NOT A FREE NAME.
23
+ *
24
+ * The api comes from the SDK being passed, so the resulting ref is
25
+ * `<api>$<tag>` and multi-instance works imperatively too. A full ref is
26
+ * also accepted and is VALIDATED: its name must equal the SDK's api
27
+ * slug, or it is `station_instance_api`.
28
+ *
29
+ * Both forms are needed because the imperative path is where the api is
30
+ * implicit in an argument rather than written in a key. An `as` that
31
+ * took an arbitrary name would reintroduce exactly the second-identity
32
+ * problem the ref re-key removed: under the ref invariant
33
+ * `as: 'solar-eu'` would denote the untagged `solar-eu` DEFINITION, not
34
+ * an instance of the SDK just handed in, and registry grouping, api
35
+ * defaults and every ref consumer would disagree about what it is.
36
+ *
37
+ * A bare connect(SDK) with no name falls back to the descriptor slug,
38
+ * which is today's behaviour and why the single-instance case is
39
+ * unchanged to the byte. */
40
+ function instanceRef(api, fopts) {
41
+ const explicit = firstNonEmpty(fopts?.instance);
42
+ if (null != explicit) {
43
+ return checkref(checkapi(api, explicit));
44
+ }
45
+ const as = firstNonEmpty(fopts?.as);
46
+ // The bare fallback is the SLUG - a name, never a ref: a `$` in it is
47
+ // an invalid name, not an implicit tag.
48
+ if (null == as) {
49
+ if (!checkInstanceName(api)) {
50
+ throw new error_1.StationError('station_instance_api', 'invalid instance name "' + api + '": a name starts with a letter ' +
51
+ 'or `@` and uses `[a-zA-Z0-9.~_-/]`, max 1024 (§6.1)');
52
+ }
53
+ return api;
54
+ }
55
+ // A full ref is validated against the api; a `$`-less string is a TAG
56
+ // and is joined to it.
57
+ //
58
+ // §6.1 gives both branches and does not say how to disambiguate a
59
+ // `$`-less string, which is a real ambiguity because a bare name is
60
+ // itself a valid (untagged) ref: `as: 'stripe'` on api `stripe` could
61
+ // read as the untagged ref `stripe` or as tag `stripe`. It is read as
62
+ // a TAG, giving `stripe$stripe`, because §6.1 says twice and
63
+ // emphatically that `as` is a tag rather than a free name, and a rule
64
+ // with no exceptions is the one that ports the same way twenty times.
65
+ // The alternative - collapsing when the tag happens to equal the api -
66
+ // is a special case that would make `as` mean different things at
67
+ // different values. Someone who wants the untagged instance passes no
68
+ // `as` at all, which is the documented spelling for it.
69
+ return checkref(-1 === as.indexOf('$') ? api + '$' + as : checkapi(api, as));
70
+ }
71
+ // The ref grammar is the JOINT identity model's (station-and-plugin.md
72
+ // §2, plugin design §4): a name is a package-ish specifier
73
+ // (`^[a-zA-Z@][a-zA-Z0-9.~_\-/]*$`), a tag is not (`^[a-zA-Z0-9.~_-]+$`
74
+ // or empty - it MAY start with a digit because auto-tagging assigns
75
+ // integer tags, and admits neither `@` nor `/`); both cap at 1024; the
76
+ // split is on the FIRST `$`, so `a$b$c` is a good name with a bad tag.
77
+ // Discharges the C4 divergence rows that pinned instanceRef accepting
78
+ // what plugin's grammar rejects.
79
+ const REF_NAME_RE = /^[a-zA-Z@][a-zA-Z0-9.~_\-\/]*$/;
80
+ const REF_TAG_RE = /^[a-zA-Z0-9.~_-]+$/;
81
+ const REF_MAX = 1024;
82
+ function checkInstanceName(name) {
83
+ if ('string' !== typeof name) {
84
+ return false;
85
+ }
86
+ if (0 === name.length || REF_MAX < name.length) {
87
+ return false;
88
+ }
89
+ return REF_NAME_RE.test(name);
90
+ }
91
+ function checkInstanceTag(tag) {
92
+ if ('string' !== typeof tag) {
93
+ return false;
94
+ }
95
+ // The empty tag is an ordinary tag: the single-instance case writes
96
+ // no tag and never learns tags exist.
97
+ if (0 === tag.length) {
98
+ return true;
99
+ }
100
+ if (REF_MAX < tag.length) {
101
+ return false;
102
+ }
103
+ return REF_TAG_RE.test(tag);
104
+ }
105
+ /** Validate a ref against the joint grammar and return its CANONICAL
106
+ * spelling: a trailing `$` (empty tag) is never kept, so `stripe$` and
107
+ * `stripe` are one registry key rather than two. */
108
+ function checkref(ref) {
109
+ const cut = ref.indexOf('$');
110
+ const name = -1 === cut ? ref : ref.substring(0, cut);
111
+ const tag = -1 === cut ? '' : ref.substring(cut + 1);
112
+ if (!checkInstanceName(name)) {
113
+ throw new error_1.StationError('station_instance_api', 'invalid instance name "' + name + '" in ref "' + ref + '": a name ' +
114
+ 'starts with a letter or `@` and uses `[a-zA-Z0-9.~_-/]`, max 1024 (§6.1)');
115
+ }
116
+ if (!checkInstanceTag(tag)) {
117
+ throw new error_1.StationError('station_instance_api', 'invalid instance tag "' + tag + '" in ref "' + ref + '": a tag ' +
118
+ 'uses `[a-zA-Z0-9.~_-]`, max 1024 (§6.1)');
119
+ }
120
+ return '' === tag ? name : ref;
121
+ }
122
+ function checkapi(api, ref) {
123
+ if ((0, profilecore_1.refapi)(ref) !== api) {
124
+ throw new error_1.StationError('station_instance_api', 'instance "' + ref + '" names api "' + (0, profilecore_1.refapi)(ref) + '", but the SDK ' +
125
+ 'passed is api "' + api + '"; `as` is a tag, not a free name (§6.1)');
126
+ }
127
+ return ref;
128
+ }
129
+ class Station {
130
+ /** §6.2's second path, and the front door the docs name.
131
+ *
132
+ * The package exported only the free `provide()` and the class had no
133
+ * static — so the documented `Station.provide(...)` call failed, and
134
+ * so did the remediation `station_no_factory` prints, which tells the
135
+ * user to make exactly that call. Delegates to the same
136
+ * process-global table the free function fills; there is one
137
+ * registry, not two. */
138
+ static provide(api, factory) {
139
+ (0, factory_1.provide)(api, factory);
140
+ }
141
+ // Ambient instance (design §10.2): open() is the idempotent
142
+ // process-wide singleton; a second open() with conflicting options is
143
+ // an error; `new Station(opts)` stays isolated for tests and
144
+ // multi-tenant hosts. open() is non-blocking - solo involves no
145
+ // network, and the deferred proxy probe must never change that.
146
+ static open(opts) {
147
+ const key = JSON.stringify(opts || {});
148
+ if (null != Station.ambient) {
149
+ if (key !== Station.ambientOpts) {
150
+ throw new error_1.StationError('station_open_conflict', 'Station.open() was already called with different options');
151
+ }
152
+ return Station.ambient;
153
+ }
154
+ Station.ambient = new Station(opts);
155
+ Station.ambientOpts = key;
156
+ return Station.ambient;
157
+ }
158
+ // The ambient instance, or null - never creates one. The generated
159
+ // station feature binds through this when no explicit handle rides
160
+ // its options (design §3.1: binding is never implicit; only open()
161
+ // creates the ambient instance).
162
+ static current() {
163
+ return Station.ambient;
164
+ }
165
+ // Test seam: drop the ambient instance.
166
+ static reset() {
167
+ Station.ambient = null;
168
+ Station.ambientOpts = null;
169
+ }
170
+ constructor(opts) {
171
+ this.registry = new Map();
172
+ // §6.1: `sdk(name)` caches; `create()` deliberately does not.
173
+ this.clients = new Map();
174
+ // The raw config, kept for §8.7's provenance: the resolved profile
175
+ // has already collapsed the levels that provenance has to name.
176
+ this.raw = null;
177
+ this.repoScoped = true;
178
+ /** An auto-assigned tag to the DECLARED instance it stands for
179
+ * (§5.3). Kept beside the registry rather than inside it because the
180
+ * mapping exists before construction, and `blockFor` needs it during
181
+ * registration. */
182
+ this.aliasOf = new Map();
183
+ this.closed = false;
184
+ // §7.4: THE DESCRIPTOR IS SHARED, because it describes the api rather
185
+ // than any use of it. `normalizeDescriptor` runs once per api and
186
+ // every instance of that api holds a reference to the same object - at
187
+ // 26 instances over 20 apis that is 20 normalizations, not 26, and the
188
+ // canonical serialization the proxy dedupes registrations by is
189
+ // computed once per api too.
190
+ //
191
+ // Keyed by the slug the config carries, which is available before
192
+ // normalization only from the config itself, so the miss path
193
+ // normalizes and then keys on the result.
194
+ this.descriptorCache = new Map();
195
+ this.opts = opts || {};
196
+ const config = undefined !== this.opts.config
197
+ ? this.opts.config
198
+ : (null != configfileio ? configfileio.loadConfig(this.opts.folder) : null);
199
+ // §6.3: an in-code config is repo-scoped by construction - the
200
+ // application wrote it. A file is repo-scoped unless it came from
201
+ // ~/.voxgig/station.json.
202
+ // Explicit wins, then an in-code config (the application wrote it,
203
+ // so it is repo-scoped by construction), then where the file was
204
+ // found. Inferring BEFORE reading the explicit option was a real
205
+ // precedence bug: it made `repoScoped: false` unsettable for any
206
+ // caller passing a config in code, which is every test of the rule.
207
+ this.repoScoped = this.opts.repoScoped
208
+ ?? (undefined !== this.opts.config
209
+ ? true
210
+ : (null == configfileio ||
211
+ 'user' !== configfileio.configScope(this.opts.folder)));
212
+ // Normalize, then validate (design §4.2). A malformed station.json
213
+ // fails open() with EVERY error at once - an eighteen-instance
214
+ // config must not die because the eighteenth has a typo'd package
215
+ // name.
216
+ //
217
+ // resolveProfile then reads the RAW config, NOT the normalized one.
218
+ // The normalized form is an input to validation and to nothing
219
+ // else: block defaults synthesized before the profile merge would
220
+ // let a one-key overlay overwrite the base's `active: false` and
221
+ // silently re-enable a barred integration (§3.3, §4.2).
222
+ if (null != config) {
223
+ (0, shape_1.validateConfig)((0, shape_1.normalizeConfig)(config));
224
+ }
225
+ this.raw = config ?? null;
226
+ this.profile = (0, profilecore_1.resolveProfile)(config ?? null, (0, profilecore_1.selectProfile)(this.opts.profile));
227
+ this.broker = new secrets_1.SecretBroker(this.profile.providers);
228
+ this.buffer = new events_1.EventBuffer();
229
+ const proxy = this.opts.proxy ?? 'auto';
230
+ this.requireProxy = 'require' === proxy;
231
+ if ('auto' === proxy) {
232
+ // The probe is deferred with the proxy itself; absence degrades
233
+ // to solo with a single warning event naming the cause (§14).
234
+ this.emit({
235
+ t: Date.now(), kind: 'station',
236
+ meta: { warn: 'proxy absent (not found); running solo' },
237
+ });
238
+ }
239
+ }
240
+ // --- binding forms (design §3.1) ---
241
+ // connect(SDK, opts): station constructs the SDK itself, activating
242
+ // the adapter with §3.3 ordering. The activation entry plus the
243
+ // extend-supplied instance ride the tolerance added to the generated
244
+ // constructor (sdkgen §9.3 change).
245
+ connect(SDK, opts) {
246
+ return this.construct(SDK, opts);
247
+ }
248
+ // adopt(SDK, opts): the retrofit path - construction-time sugar, not
249
+ // post-hoc attachment (§3.1). In ts it is the same construction as
250
+ // connect; a resident options.apikey is hoisted by the adapter.
251
+ adopt(SDK, opts) {
252
+ return this.construct(SDK, opts);
253
+ }
254
+ construct(SDK, opts) {
255
+ if (this.closed) {
256
+ throw new error_1.StationError('station_no_plugin', 'station is closed');
257
+ }
258
+ opts = opts || {};
259
+ const fmap = { ...(opts.feature || {}) };
260
+ fmap['station'] = {
261
+ ...(fmap['station'] || {}),
262
+ active: true, station: this, calleropts: opts,
263
+ // §6.1: `as` is a TAG, resolved against the api in _register -
264
+ // the api comes from the SDK being passed and is not knowable
265
+ // here until that SDK's config has been normalized.
266
+ ...(null == opts.as ? {} : { as: opts.as }),
267
+ ...(null == opts.instance ? {} : { instance: opts.instance }),
268
+ };
269
+ const options = {
270
+ ...opts,
271
+ feature: fmap,
272
+ // The carried adapter rides extend for SDKs generated WITHOUT
273
+ // the station feature; when the generated class exists the
274
+ // constructor uses it and the extend copy is skipped by name
275
+ // (both delegate to featureBinding, so behavior is identical).
276
+ extend: [...(opts.extend || []), (0, adapter_1.adapterFeature)(this, opts)],
277
+ };
278
+ return new SDK(options);
279
+ }
280
+ // Inverted binding (design §3.1): build the plain options map a
281
+ // generated constructor already accepts - the handle, the activation
282
+ // entry, and the profile's per-plugin base (applied here, at
283
+ // options-build time, so caller opts passed in `extra` still win).
284
+ // §6.1: `options(instanceName?, extra?)`. The name is optional and
285
+ // leading, so every existing `options({...})` call is unchanged - the
286
+ // inverted binding is the static languages' path and they need to say
287
+ // which instance they are building without a second method.
288
+ options(a, b) {
289
+ const named = 'string' === typeof a;
290
+ const instance = named ? a : undefined;
291
+ const extra = (named ? b : a) || {};
292
+ const fmap = { ...(extra.feature || {}) };
293
+ fmap['station'] = {
294
+ ...(fmap['station'] || {}),
295
+ active: true, station: this, calleropts: extra,
296
+ ...(null == instance ? {} : { instance }),
297
+ };
298
+ return { ...extra, feature: fmap };
299
+ }
300
+ // --- registration (design §3 item 1, called by the adapter) ---
301
+ // The registry entry whose client IS this object, or null. Used by
302
+ // featureBinding for idempotency: connect/adopt activate the station
303
+ // entry AND ride the carried adapter on extend, so on an SDK whose
304
+ // generated config carries a real station feature class the same
305
+ // construction reaches featureBinding twice - the second arrival
306
+ // must no-op, while a genuinely second client of the same SDK class
307
+ // still fails _register's slug check (§10.2).
308
+ _boundEntry(client) {
309
+ for (const entry of this.registry.values()) {
310
+ if (entry.client === client) {
311
+ return entry;
312
+ }
313
+ }
314
+ return null;
315
+ }
316
+ /** The profile block that governs an instance — its own if the
317
+ * profile declares it, otherwise its **api's**.
318
+ *
319
+ * `resolveProfile` builds `profile.sdk` from the declared refs alone
320
+ * ("an api block declares no instance, so the ref set comes from the
321
+ * two `sdk` maps"), shallow-merging `profile.api[a]` into each. That
322
+ * is right for a declared instance and leaves an IMPERATIVE one —
323
+ * `connect(SDK, { as: 'test' })`, named but never written into
324
+ * config — with no block at all. The api-level `secret`, `base` and
325
+ * most seriously `policy.hosts` then did not reach it, so a profile
326
+ * that denies egress everywhere denied nothing for a tagged client.
327
+ *
328
+ * ONE RULE, ONE PLACE: registration and the transport seam both ask
329
+ * here, because they disagreeing is how the credential and the
330
+ * allowlist came apart in the first place. */
331
+ blockFor(name) {
332
+ return this.profile.sdk[this.declaredRef(name)] ??
333
+ this.profile.api[(0, profilecore_1.refapi)(name)];
334
+ }
335
+ /** The DECLARED instance an assigned tag stands for, or the name
336
+ * itself. `create('stripe$prod')` registers under `stripe$1`, and
337
+ * every question about that client's configuration — its secret, its
338
+ * base, its egress policy — is a question about `stripe$prod`. */
339
+ declaredRef(name) {
340
+ return this.aliasOf.get(name) ?? name;
341
+ }
342
+ _register(client, config, options, _calleropts, fopts) {
343
+ const { descriptor, warnings } = this.describe(config, options.feature);
344
+ const api = descriptor.slug;
345
+ // §7.5: station knows the instance name before construction begins
346
+ // and passes it through the feature options. A bare connect(SDK)
347
+ // with no name falls back to the descriptor slug, which is today's
348
+ // behaviour and why the single-instance case is unchanged.
349
+ const name = instanceRef(api, fopts);
350
+ // §7.1: the check moves to the instance key. Two clients of one api
351
+ // is the NORMAL case now; two bindings of one instance is still the
352
+ // error it was.
353
+ if (this.registry.has(name)) {
354
+ throw new error_1.StationError('station_bound_twice', 'instance "' + name + '" is already registered; binding one client ' +
355
+ 'twice is an error (§10.2)');
356
+ }
357
+ const profilePlugin = this.blockFor(name);
358
+ // Secret name precedence: the feature option (in-code, design §9
359
+ // config.options.secret) beats the profile, which beats the
360
+ // INSTANCE-derived default.
361
+ //
362
+ // §5.1: `secretnameDefault` takes the instance name, not the slug.
363
+ // For an untagged instance the two are the same string, so the
364
+ // single-instance case is unchanged to the byte - `voxgig-solardemo`
365
+ // still derives `voxgig_solardemo.apikey` and still reads
366
+ // VOXGIG_SOLARDEMO_APIKEY. `stripe$test` derives
367
+ // `stripe_test.apikey`, because each instance IS a separate
368
+ // credentialed use of the API.
369
+ //
370
+ // The descriptor's own `auth.secretname` stays the API-level
371
+ // default and is NOT used here (§7.4): one descriptor is shared by
372
+ // every instance of an api and cannot hold two instance-derived
373
+ // names, so whichever instance built the cached copy would report
374
+ // the other's secret metadata wrongly. This is the authority; that
375
+ // field is documentation.
376
+ // ...and the DEFAULT takes the declared name too, not the assigned
377
+ // tag: `stripe$1` created from `stripe$test` derives
378
+ // `stripe_test.apikey`, so every per-request client of one instance
379
+ // shares one broker cache entry (§5.3).
380
+ const secretname = firstNonEmpty(fopts?.secret, profilePlugin?.secret) ||
381
+ (0, descriptor_1.secretnameDefault)(this.declaredRef(name));
382
+ const rung = descriptor.auth.active ? 'R1' : 'none';
383
+ const binding = {
384
+ plugin: name,
385
+ instance: api,
386
+ // §7.2: two live instances of one api MUST have distinct
387
+ // placeholders or the injection seam cannot tell which credential
388
+ // a header wants.
389
+ placeholder: descriptor.auth.active ? (0, secrets_1.placeholderFor)(name) : undefined,
390
+ secretname: descriptor.auth.active ? secretname : undefined,
391
+ rung,
392
+ };
393
+ this.registry.set(name, {
394
+ name, api, descriptor, rung, client, warnings,
395
+ secretname: descriptor.auth.active ? secretname : undefined,
396
+ });
397
+ for (const w of warnings) {
398
+ this.emit({
399
+ t: Date.now(), kind: 'station', plugin: name, api,
400
+ meta: { warn: w },
401
+ });
402
+ }
403
+ this.emit({
404
+ t: Date.now(), kind: 'construct', plugin: name, api,
405
+ meta: { name: descriptor.name, version: descriptor.version, rung },
406
+ });
407
+ return { binding, profilePlugin };
408
+ }
409
+ /** The descriptor describes the API, and is SHARED by every instance
410
+ * of it — which is §7.4's own reasoning for why the effective secret
411
+ * name moved to `Binding` and is not read off the descriptor.
412
+ *
413
+ * The same argument applies to feature activation, and this did not
414
+ * follow it: the cache is keyed by slug alone while
415
+ * `normalizeDescriptor`'s second argument decides each feature row's
416
+ * `active`. So two instances of one api constructed with different
417
+ * feature maps shared the FIRST one's feature state, and
418
+ * `descriptorOf()` / `canonicalDescriptor()` became
419
+ * construction-order-dependent.
420
+ *
421
+ * Normalized with no per-instance features, so the shared value holds
422
+ * only API-stable metadata — which is what `factory.ts` already does
423
+ * when it normalizes at provide time. Per-instance activation is
424
+ * `featuresOf(name)`'s answer, and always was. */
425
+ describe(config, _feature) {
426
+ const slug = String(config?.main?.slug ?? '');
427
+ if ('' !== slug) {
428
+ const hit = this.descriptorCache.get(slug);
429
+ if (null != hit) {
430
+ return hit;
431
+ }
432
+ }
433
+ const out = (0, descriptor_1.normalizeDescriptor)(config, undefined);
434
+ this.descriptorCache.set(out.descriptor.slug, out);
435
+ return out;
436
+ }
437
+ _hoist(name, value) {
438
+ this.broker.hoist(name, value);
439
+ this.emit({
440
+ t: Date.now(), kind: 'station', plugin: name, api: (0, profilecore_1.refapi)(name),
441
+ meta: {
442
+ warn: 'a resident credential was hoisted into the broker and ' +
443
+ 'replaced by the placeholder; prefer configuring the secret ' +
444
+ 'name and letting sekreto resolve it',
445
+ },
446
+ });
447
+ }
448
+ // --- the transport middleware (design §3.3, §5.3) ---
449
+ async _transport(name, inner, fctx, fullurl, fetchdef) {
450
+ // Fail-closed means traffic (§2.1): with the proxy deferred,
451
+ // `require` can never attach, so every operation fails here - the
452
+ // operation path, never the constructor.
453
+ if (this.requireProxy) {
454
+ const err = new error_1.StationError('station_no_proxy', 'proxy: "require" is set and no proxy is attached');
455
+ this.emitErr(name, fctx, err);
456
+ return err;
457
+ }
458
+ const entry = this.registry.get(name);
459
+ const placeholder = (0, secrets_1.placeholderFor)(name);
460
+ const live = 'live' === fctx.client._mode;
461
+ const profilePlugin = this.blockFor(name);
462
+ // Policy mode (design §16): `live` is the default; `block` is the
463
+ // kill switch and refuses live egress outright. Enforced at the
464
+ // same seam as the hosts allowlist, and like it only on LIVE
465
+ // traffic - a test-mode client's mock transport is not egress.
466
+ //
467
+ // §14 names no mode-specific code, so `block` raises
468
+ // `station_host_allow` - the closest existing catalog code: the
469
+ // same `_allow` gate grammar, the same seam, the same meaning
470
+ // (egress denied by this plugin's policy), with the message naming
471
+ // the mode. `record`/`replay`/`mock` are proxy-era modes accepted
472
+ // by the grammar now (so a config written for the proxy is not a
473
+ // validation error) and fail `station_no_proxy` on the operation
474
+ // path until a proxy is attached - the same fail-closed behaviour
475
+ // `require` shows above.
476
+ const mode = profilePlugin?.policy?.mode ?? 'live';
477
+ if ('live' !== mode && live) {
478
+ const err = 'block' === mode
479
+ ? new error_1.StationError('station_host_allow', 'egress denied: plugin "' + name + '" is policy mode "block", ' +
480
+ 'the kill switch (§16)')
481
+ : new error_1.StationError('station_no_proxy', 'policy mode "' + mode + '" for plugin "' + name + '" needs an ' +
482
+ 'attached proxy, and none is attached');
483
+ this.emitErr(name, fctx, err);
484
+ return err;
485
+ }
486
+ // Egress policy (design §16), solo half: the hosts allowlist is
487
+ // enforced at the seam every request crosses. When a policy is
488
+ // present, redirects come back manual - a 3xx is a response like
489
+ // any other, so a Location off the allowlist cannot pull an
490
+ // automatic credentialed follow-up to an unapproved host (§8.2's
491
+ // rule, applied at the library seam).
492
+ const hosts = profilePlugin?.policy?.hosts;
493
+ if (null != hosts && live) {
494
+ let hostname = '';
495
+ try {
496
+ hostname = new URL(fullurl).hostname;
497
+ }
498
+ catch (_e) { }
499
+ if (!hosts.includes(hostname)) {
500
+ const err = new error_1.StationError('station_host_allow', 'egress to "' + hostname + '" denied by the hosts policy of ' +
501
+ 'plugin "' + name + '"');
502
+ this.emitErr(name, fctx, err);
503
+ return err;
504
+ }
505
+ }
506
+ let senddef = fetchdef;
507
+ if (null != hosts && live) {
508
+ senddef = { ...senddef, redirect: 'manual' };
509
+ }
510
+ // Injection: at the last boundary, below every recording feature,
511
+ // and never into mock transports (§3.3) - in test/mock modes the
512
+ // placeholder rides through untouched, so real credentials never
513
+ // enter in-memory mock stores. Copy-on-inject: the object graph
514
+ // reachable from ctx/spec/ctrl keeps the placeholder, ever (§5.3).
515
+ if (live && null != entry && 'R1' === entry.rung) {
516
+ // §7.4: THE EFFECTIVE NAME, resolved once at registration and
517
+ // stored on the entry. Re-deriving it here got the precedence
518
+ // right and the FALLBACK wrong: `descriptor.auth.secretname` is
519
+ // the API-level default, and one descriptor is shared by every
520
+ // instance of an api — so a tagged instance with no explicit
521
+ // `secret` read `stripe.apikey` where registration had recorded
522
+ // `stripe_test.apikey`. Either the request fails despite the
523
+ // credential being configured, or it succeeds with a sibling's.
524
+ //
525
+ // No fallback, and the `!` is the invariant rather than a shrug:
526
+ // this branch is guarded by `'R1' === entry.rung`, which is set
527
+ // only when `descriptor.auth.active` — the same condition under
528
+ // which `entry.secretname` is populated. Substituting a different
529
+ // name when it is absent is the bug above, written again.
530
+ const secretname = entry.secretname;
531
+ let value;
532
+ try {
533
+ value = await this.broker.value(name, secretname);
534
+ }
535
+ catch (e) {
536
+ this.emitErr(name, fctx, e);
537
+ return e instanceof Error ? e : new Error(String(e));
538
+ }
539
+ senddef = { ...senddef, headers: { ...(senddef.headers || {}) } };
540
+ for (const h of Object.keys(senddef.headers)) {
541
+ const v = senddef.headers[h];
542
+ if ('string' === typeof v && v.includes(placeholder)) {
543
+ senddef.headers[h] = v.split(placeholder).join(value);
544
+ }
545
+ }
546
+ }
547
+ const corr = fctx.station$?.corr;
548
+ const started = Date.now();
549
+ let res;
550
+ try {
551
+ res = await inner(fctx, fullurl, senddef);
552
+ }
553
+ catch (e) {
554
+ this.emitHttp(name, corr, fullurl, senddef, 0, started, 0);
555
+ this.emitErr(name, fctx, e);
556
+ throw e;
557
+ }
558
+ if (res instanceof Error) {
559
+ this.emitHttp(name, corr, fullurl, senddef, 0, started, 0);
560
+ this.emitErr(name, fctx, res);
561
+ return res;
562
+ }
563
+ let bytes = 0;
564
+ const cl = res?.headers?.get?.('content-length');
565
+ if (null != cl) {
566
+ bytes = parseInt(cl, 10) || 0;
567
+ }
568
+ this.emitHttp(name, corr, fullurl, senddef, res?.status || 0, started, bytes);
569
+ return res;
570
+ }
571
+ emitHttp(slug, corr, fullurl, fetchdef, status, started, bytes) {
572
+ let host = '', path = '';
573
+ try {
574
+ const u = new URL(fullurl);
575
+ host = u.host;
576
+ path = u.pathname;
577
+ }
578
+ catch (_e) {
579
+ path = fullurl;
580
+ }
581
+ this.emit({
582
+ t: started, kind: 'http', plugin: slug, api: (0, profilecore_1.refapi)(slug), corr,
583
+ http: {
584
+ method: fetchdef?.method || 'GET', host, path, status,
585
+ durationMs: Date.now() - started, bytes,
586
+ },
587
+ });
588
+ }
589
+ emitErr(name, fctx, err) {
590
+ this.emit({
591
+ // §7.3's grouping contract: `plugin` is the INSTANCE and `api` is
592
+ // what groups its siblings. Construction events carried both and
593
+ // the runtime ones did not, so a consumer could group `construct`
594
+ // by api and then get `api: undefined` for every request, error
595
+ // and hoist from the same client — the grouping working exactly
596
+ // until it was used.
597
+ t: Date.now(), kind: 'error', plugin: name, api: (0, profilecore_1.refapi)(name),
598
+ corr: fctx?.station$?.corr,
599
+ err: {
600
+ code: err?.code,
601
+ // The scrub keeps an upstream echo of a credential out of the
602
+ // event stream (§7 as revised: exact-value, no length floor).
603
+ message: this.redact(String(err?.message || err)),
604
+ },
605
+ });
606
+ }
607
+ // Op events from the hook bridge (design §3 item 3).
608
+ _opEvent(name, ctx, outcome) {
609
+ const st = ctx.station$ || {};
610
+ this.emit({
611
+ t: Date.now(), kind: 'op', plugin: name, api: (0, profilecore_1.refapi)(name), corr: st.corr,
612
+ // ctx.op is the SDK's resolved Operation: name + entity, in the
613
+ // descriptor's lowercase spelling.
614
+ op: {
615
+ entity: String(ctx.op?.entity ?? ctx.entity?.name ?? ''),
616
+ op: String(ctx.op?.name ?? ''),
617
+ outcome,
618
+ durationMs: null != st.start ? Date.now() - st.start : 0,
619
+ },
620
+ });
621
+ }
622
+ // --- the query/observe surface (design §3.2, §6) ---
623
+ // One entry per LIVE INSTANCE (§6.1), and exhaustive: auto-tagged
624
+ // entries are not collapsed here, because inspection, health
625
+ // reporting and cleanup all need to enumerate the clients `create()`
626
+ // produced, which is exactly when you most want them. Truncation is a
627
+ // presentation decision and belongs to `status()`.
628
+ plugins() {
629
+ return Array.from(this.registry.values()).map((e) => ({
630
+ name: e.name,
631
+ api: e.api,
632
+ // Retained: it is the api, which is what `slug` always meant here,
633
+ // and dropping it would break every consumer for no gain while
634
+ // the two are equal for untagged instances.
635
+ slug: e.api,
636
+ descriptor: e.descriptor,
637
+ rung: e.rung,
638
+ secretname: e.secretname,
639
+ warnings: e.warnings.slice(),
640
+ }));
641
+ }
642
+ // --- the declarative front door (design §6) ---
643
+ /** The instance, constructed on first call and CACHED: same name ->
644
+ * same object. That caching is what makes "get it where you need it"
645
+ * a real instruction - call it in a request handler, in a worker, in
646
+ * a test, and the first call pays construction while the rest are a
647
+ * map lookup.
648
+ *
649
+ * SYNCHRONOUS (§6.3), which is what bounds the loader to CommonJS. */
650
+ sdk(name) {
651
+ const cached = this.clients.get(name);
652
+ if (null != cached) {
653
+ return cached;
654
+ }
655
+ const client = this.build(name, undefined);
656
+ this.clients.set(name, client);
657
+ return client;
658
+ }
659
+ /** An UNCACHED client from the same resolved config plus overrides,
660
+ * for the case that genuinely wants a distinct one - a per-request
661
+ * credential scope, a test double. Deliberately the longer name.
662
+ *
663
+ * It registers under an AUTO-ASSIGNED TAG, because §7.5 registers
664
+ * every constructed adapter under its instance name and
665
+ * `station_bound_twice` fires on a second binding of one name: a
666
+ * second `create('stripe')` would otherwise throw, which is exactly
667
+ * the per-request case this exists for. The tag is the lowest unused
668
+ * positive integer, so an auto-tagged instance is an ORDINARY
669
+ * instance rather than a parallel identity scheme - `plugins()`, the
670
+ * placeholder, the event stream and `station_bound_twice` all keep
671
+ * working on one identity model.
672
+ *
673
+ * The SECRET NAME does not follow the assigned tag: it resolves from
674
+ * the DECLARED instance the tag was assigned under, so every client
675
+ * of one instance shares one broker cache entry rather than
676
+ * re-resolving per request (§5.3). */
677
+ create(name, overrides) {
678
+ return this.build(name, this.autotag(name), overrides);
679
+ }
680
+ /** The lowest positive integer tag not already taken, by a LIVE
681
+ * instance or a DECLARED one.
682
+ *
683
+ * The registry alone was not enough: a profile may declare
684
+ * `stripe$1`, and until something constructs it `registry.has` says
685
+ * false — so `create('stripe$prod')` took that identity for a client
686
+ * built from the `stripe$prod` block. `instances()` then reported the
687
+ * declared `stripe$1` as live with the wrong client, and a later
688
+ * `sdk('stripe$1')` failed `station_bound_twice` against a binding
689
+ * that was never its own. Declaration reserves the name whether or
690
+ * not it has been built. */
691
+ autotag(name) {
692
+ const api = (0, profilecore_1.refapi)(name);
693
+ for (let n = 1;; n++) {
694
+ const ref = api + '$' + n;
695
+ if (!this.registry.has(ref) && null == this.profile.sdk[ref]) {
696
+ return ref;
697
+ }
698
+ }
699
+ }
700
+ build(name, as, overrides) {
701
+ if (this.closed) {
702
+ throw new error_1.StationError('station_no_plugin', 'station is closed');
703
+ }
704
+ const block = this.profile.sdk[name];
705
+ if (null == block) {
706
+ throw new error_1.StationError('station_no_instance', 'no declared instance "' + name + '"; declared: [' +
707
+ Object.keys(this.profile.sdk).sort().join(', ') + ']');
708
+ }
709
+ if (false === block.active) {
710
+ throw new error_1.StationError('station_instance_inactive', 'instance "' + name + '" is declared with `active: false`, which ' +
711
+ 'bars it from running while keeping it visible in instances()');
712
+ }
713
+ const api = (0, profilecore_1.refapi)(name);
714
+ const entry = this.resolveFactory(api, block);
715
+ // §8.5 VALIDATES HERE, not only in `check()`. The schema arrives
716
+ // with the factory, so the moment a factory is resolved is the
717
+ // first moment validation is possible — and it was running in
718
+ // `check()` alone. Two gaps followed: production `sdk()` silently
719
+ // ignored an unknown option like `retry.retires`, and `check()`
720
+ // itself missed the case where the factory is discovered by the
721
+ // LOADER (its pre-check sees no registered factory, then `sdk()`
722
+ // loads and constructs unvalidated). One call here closes both,
723
+ // because every path to a constructor comes through this line.
724
+ const faults = (0, feature_1.checkfeatures)(this.featuresOf(name).merged, entry.descriptor);
725
+ if (0 < faults.length) {
726
+ // `Fault.code` is a plain string in `feature.ts`; the two codes it
727
+ // actually produces are both in the union, and `check()` passes
728
+ // the same value through untyped. Narrowed here rather than
729
+ // widening the union, so a new fault code is a compile error at
730
+ // the place that has to decide what it means.
731
+ throw new error_1.StationError(faults[0].code, faults.map((f) => f.message).join('; '));
732
+ }
733
+ // §8.4: compose the merged feature map into the ORDERED form and
734
+ // hand it to the constructor. No new seam - it is the same
735
+ // `options.feature` map `connect()` already uses for station's own
736
+ // placement, with more in it, and a JS object preserves the
737
+ // insertion order of string keys so the order rides the map.
738
+ //
739
+ // Station's own entry is composed AFTER the user merge and always
740
+ // wins (§8.4), which is why `station` is dropped here and added by
741
+ // `options()`: a config file that can switch off the component
742
+ // reading it is not a surface, it is a trap. `feature.station` is
743
+ // already `station_feature_reserved` at validation, so this is the
744
+ // second half of one rule rather than a second rule.
745
+ const resolved = this.featuresOf(name);
746
+ const fmap = {};
747
+ for (const f of (0, feature_1.composefeatures)((0, feature_1.resolveorder)(resolved.merged).filter((o) => 'station' !== o.name))) {
748
+ const { name: fname, ...rest } = f;
749
+ fmap[fname] = rest;
750
+ }
751
+ const opts = {
752
+ ...(block.options || {}),
753
+ ...(null == block.base ? {} : { base: block.base }),
754
+ ...(overrides || {}),
755
+ feature: { ...fmap, ...((overrides || {}).feature || {}) },
756
+ };
757
+ // §5.3, and `create`'s own doc comment: "the SECRET NAME does not
758
+ // follow the assigned tag: it resolves from the DECLARED instance
759
+ // the tag was assigned under."
760
+ //
761
+ // THE ALIAS IS RECORDED, NOT THE FIELDS. The first fix for this
762
+ // carried the declared `secret` through the feature options and
763
+ // stopped there — which left `policy`, `base` and everything else
764
+ // behind, so an auto-tagged client silently lost its declared
765
+ // instance's HOSTS ALLOWLIST and fell back to the wider api-level
766
+ // one. Carrying configuration a field at a time is how that
767
+ // happens; recording what the tag STANDS FOR is one rule that every
768
+ // lookup already goes through.
769
+ //
770
+ // Only when the tag was ASSIGNED — a caller naming its own is
771
+ // naming an instance, not aliasing one.
772
+ if (null != as && as !== name) {
773
+ this.aliasOf.set(as, name);
774
+ }
775
+ // ...AND THE CARRIED ADAPTER RIDES EXTEND, exactly as it does on
776
+ // `connect`. §3.1's retrofit case — an SDK generated before the
777
+ // station feature, which `factoryFromModule` explicitly supports —
778
+ // has no generated feature to consume the `feature.station`
779
+ // activation this path sets, so declarative `sdk()` either failed
780
+ // on an unknown feature or returned an unregistered, unwrapped
781
+ // client with no credential injection and no events. The imperative
782
+ // path carried it and the declarative one did not, which is the
783
+ // whole defect.
784
+ //
785
+ // Safe on a REGENERATED SDK too: the constructor uses its own
786
+ // station feature and skips the extend copy by name, and both
787
+ // delegate to `featureBinding`, whose `_boundEntry` check no-ops a
788
+ // second arrival for the same client.
789
+ const withAdapter = {
790
+ ...opts,
791
+ extend: [...(opts.extend || []), (0, adapter_1.adapterFeature)(this, opts)],
792
+ };
793
+ // The instance name reaches the adapter the same way it does on the
794
+ // imperative path, so registration has one spelling (§7.5).
795
+ return entry.construct(this.options(as ?? name, withAdapter));
796
+ }
797
+ /** §6.2's three paths, in order of preference: self-registration,
798
+ * `Station.provide`, then the loader. */
799
+ resolveFactory(api, block) {
800
+ const direct = (0, factory_1.factoryFor)(api);
801
+ if (null != direct) {
802
+ return direct;
803
+ }
804
+ const pkg = this.loaderPackage(api, block);
805
+ if (null != pkg) {
806
+ (0, loader_1.loadSync)(api, pkg, block.export);
807
+ const loaded = (0, factory_1.factoryFor)(api);
808
+ if (null != loaded) {
809
+ return loaded;
810
+ }
811
+ }
812
+ throw new error_1.StationError('station_no_factory', 'no factory for api "' + api + '"; either link a generated package ' +
813
+ 'that self-registers, call Station.provide("' + api + '", ...), or ' +
814
+ 'set `api.' + api + '.package` so the loader can import it');
815
+ }
816
+ /** `package` is honoured only from repo-scoped config (§6.3), and a
817
+ * user-level one is IGNORED WITH A WARNING rather than imported - it
818
+ * names code to load and sits outside the repo's review boundary. */
819
+ loaderPackage(api, block) {
820
+ const pkg = block.package;
821
+ if (null == pkg || '' === pkg) {
822
+ return undefined;
823
+ }
824
+ if (false === this.opts.load) {
825
+ return undefined;
826
+ }
827
+ if (!this.repoScoped) {
828
+ this.emit({
829
+ t: Date.now(), kind: 'station', plugin: api, api,
830
+ meta: {
831
+ warn: 'ignoring `package` for api "' + api + '": it came from a ' +
832
+ 'user-level station.json, which is outside the repo\'s review ' +
833
+ 'boundary; everything else in that config still applies',
834
+ },
835
+ });
836
+ return undefined;
837
+ }
838
+ return pkg;
839
+ }
840
+ /** ts/js only: preload ESM packages into the factory table, after
841
+ * which `sdk()` is synchronous again for everything (§6.3). One
842
+ * `await` at startup rather than one per call site. */
843
+ async load() {
844
+ if (false === this.opts.load) {
845
+ return;
846
+ }
847
+ for (const name of Object.keys(this.profile.sdk).sort()) {
848
+ const block = this.profile.sdk[name];
849
+ if (false === block.active) {
850
+ continue;
851
+ }
852
+ const api = (0, profilecore_1.refapi)(name);
853
+ if (null != (0, factory_1.factoryFor)(api)) {
854
+ continue;
855
+ }
856
+ const pkg = this.loaderPackage(api, block);
857
+ if (null == pkg) {
858
+ continue;
859
+ }
860
+ await (0, loader_1.loadAsync)(api, pkg, block.export);
861
+ }
862
+ }
863
+ /** The merged, ordered feature set for one instance, WITH
864
+ * PROVENANCE (§8.7): which config level set each value.
865
+ *
866
+ * Provenance is the half that makes a fleet view usable rather than
867
+ * merely correct - at 26 instances "why is retry off here" is the
868
+ * question, and a merged map alone cannot answer it. */
869
+ featuresOf(name) {
870
+ const api = (0, profilecore_1.refapi)(name);
871
+ const profiles = (this.raw?.profiles || {});
872
+ const base = profiles['default'] || {};
873
+ const overlay = 'default' === this.profile.name
874
+ ? {} : (profiles[this.profile.name] || {});
875
+ const LEVELS = [
876
+ 'default.feature', 'default.api', 'default.sdk',
877
+ this.profile.name + '.feature',
878
+ this.profile.name + '.api',
879
+ this.profile.name + '.sdk',
880
+ ];
881
+ const sources = (0, feature_1.featuresources)(base, overlay, api, name);
882
+ // Last writer per (feature, key) wins, and the level that wrote it
883
+ // is what `from` records.
884
+ const from = {};
885
+ sources.forEach((src, i) => {
886
+ if (null == src || 'object' !== typeof src) {
887
+ return;
888
+ }
889
+ for (const fname of Object.keys(src)) {
890
+ const entry = src[fname];
891
+ if (null == entry || 'object' !== typeof entry) {
892
+ continue;
893
+ }
894
+ from[fname] = from[fname] || {};
895
+ for (const k of Object.keys(entry)) {
896
+ from[fname][k] = LEVELS[i];
897
+ }
898
+ }
899
+ });
900
+ let merged = (0, feature_1.mergefeatures)(sources);
901
+ // Policy budget (design §16): rps/concurrency ceilings ride "the
902
+ // SDK `ratelimit` feature, configured by station". Composed HERE,
903
+ // into the merged map every consumer reads, rather than patched in
904
+ // at construction alone - so `build()` orders it with the ordinary
905
+ // constraint-and-band rules (ordering and the station pin hold),
906
+ // `check()`'s §8.5 pass validates it against the SDK's own
907
+ // declaration (a budget on an SDK with no ratelimit feature is
908
+ // `station_feature_unknown`, not a setting that quietly did
909
+ // nothing), and the §8.7 fleet view answers "is ratelimit on?"
910
+ // truthfully, with `policy.budget` as the provenance level.
911
+ //
912
+ // `rps` maps to the token bucket's refill `rate` (per second -
913
+ // the same unit); `concurrency` to its capacity `burst`, the
914
+ // number of requests that can be in flight from a full bucket.
915
+ // POLICY WINS over a `feature.ratelimit` config entry on the keys
916
+ // it sets - it is enforcement, not a default - and other tuning
917
+ // keys survive beside it.
918
+ const budget = this.blockFor(name)?.policy?.budget;
919
+ if (null != budget && 'object' === typeof budget && !Array.isArray(budget)) {
920
+ const prior = merged.ratelimit;
921
+ const entry = {
922
+ ...(null != prior && 'object' === typeof prior ? prior : {}),
923
+ active: true,
924
+ };
925
+ from.ratelimit = from.ratelimit || {};
926
+ from.ratelimit.active = 'policy.budget';
927
+ if (null != budget.rps) {
928
+ entry.rate = budget.rps;
929
+ from.ratelimit.rate = 'policy.budget';
930
+ }
931
+ if (null != budget.concurrency) {
932
+ entry.burst = budget.concurrency;
933
+ from.ratelimit.burst = 'policy.budget';
934
+ }
935
+ merged = { ...merged, ratelimit: entry };
936
+ }
937
+ // THE IMPLICIT STATION ENTRY, added for ORDERING ONLY. `station` is
938
+ // never in `merged` — `feature.station` is reserved and rejected at
939
+ // validation (§8.4) — so `checkpin` found no station row and
940
+ // returned immediately, every time. It was a permanent no-op: a
941
+ // constraint like `retry.order.after: 'station'` was treated as
942
+ // vacuous rather than rejected, and the reported order omitted the
943
+ // one feature whose position is supposedly pinned.
944
+ //
945
+ // Added here rather than into `merged`, which stays the user's own
946
+ // merge result. `build` already filters `station` out of the map it
947
+ // hands the constructor, because §8.4 composes station's entry
948
+ // after the user merge and always wins.
949
+ const ordered = (0, feature_1.resolveorder)({ ...merged, station: { active: true } });
950
+ (0, feature_1.checkpin)(ordered);
951
+ return { ordered: ordered.map((o) => o.name), merged, from };
952
+ }
953
+ /** The fleet feature view: instance x feature, effective options, and
954
+ * which config level set each (§8.7). */
955
+ features(filter) {
956
+ // §8.7's documented shape is an OBJECT, and only the object form
957
+ // can express the question the view exists for: `{feature: 'debug'}`
958
+ // — "is debug on anywhere?", the one that is twenty greps today.
959
+ // The implementation took a bare string and compared it against
960
+ // both `name` and `api`, so every documented call returned an empty
961
+ // list, an object never equalling either string.
962
+ //
963
+ // The string form is kept as shorthand for "this instance or this
964
+ // api", because it is what the tests and the imperative path
965
+ // already use and it costs one line.
966
+ const f = 'string' === typeof filter
967
+ ? { instance: filter, api: filter, loose: true }
968
+ : { ...(filter || {}), loose: false };
969
+ const rows = this.instances()
970
+ .filter((r) => {
971
+ if (f.loose) {
972
+ return null == f.instance || r.name === f.instance || r.api === f.api;
973
+ }
974
+ if (null != f.instance && r.name !== f.instance && r.api !== f.instance) {
975
+ return false;
976
+ }
977
+ return null == f.api || r.api === f.api;
978
+ })
979
+ .map((r) => ({ instance: r.name, api: r.api, ...this.featuresOf(r.name) }));
980
+ // `feature` filters the ROWS, not the instances: an instance that
981
+ // does not carry the named feature is not part of the answer, and
982
+ // the rows that remain are narrowed to it so the view answers
983
+ // "where is debug on, and with what" rather than "here is
984
+ // everything, go and look".
985
+ const want = filter?.feature;
986
+ if (null == want) {
987
+ return rows;
988
+ }
989
+ return rows
990
+ .filter((row) => null != row.merged[want])
991
+ .map((row) => ({
992
+ instance: row.instance,
993
+ api: row.api,
994
+ ordered: row.ordered.filter((n) => n === want),
995
+ merged: { [want]: row.merged[want] },
996
+ from: { [want]: row.from[want] || {} },
997
+ }));
998
+ }
999
+ /** Eagerly resolve and construct every ACTIVE instance - for CI
1000
+ * (§6.6). The point is to turn availability errors, which are
1001
+ * deliberately deferred to first use, into one failure at a moment
1002
+ * somebody is watching. */
1003
+ check() {
1004
+ const ok = [];
1005
+ const failed = [];
1006
+ for (const row of this.instances()) {
1007
+ if (!row.active) {
1008
+ continue;
1009
+ }
1010
+ try {
1011
+ // §8.5 runs FIRST and needs no construction: the schema arrives
1012
+ // with the factory, not with a live client, so a feature typo
1013
+ // is a CI failure rather than a setting that quietly did
1014
+ // nothing in production.
1015
+ const entry = (0, factory_1.factoryFor)(row.api);
1016
+ if (null != entry) {
1017
+ const faults = (0, feature_1.checkfeatures)(this.featuresOf(row.name).merged, entry.descriptor);
1018
+ if (0 < faults.length) {
1019
+ failed.push({
1020
+ name: row.name, code: faults[0].code,
1021
+ message: faults.map((f) => f.message).join('; '),
1022
+ });
1023
+ continue;
1024
+ }
1025
+ }
1026
+ this.sdk(row.name);
1027
+ ok.push(row.name);
1028
+ }
1029
+ catch (e) {
1030
+ failed.push({
1031
+ name: row.name, code: e?.code, message: String(e?.message || e),
1032
+ });
1033
+ }
1034
+ }
1035
+ return { ok, failed };
1036
+ }
1037
+ /** Batch-resolve secrets for ACTIVE instances (§5.5).
1038
+ *
1039
+ * With no argument it warms the active ones only, because reaching
1040
+ * for a credential belonging to a disabled integration is the wrong
1041
+ * default. `warm(names)` warms exactly what it is given, inactive
1042
+ * included, because an explicit name is an explicit request. */
1043
+ async warm(names) {
1044
+ const wanted = null != names
1045
+ ? names
1046
+ : this.instances().filter((r) => r.active).map((r) => r.name);
1047
+ // CONCURRENT, not serial. Awaiting inside the loop made `warm`
1048
+ // cost the SUM of every provider round-trip, which defeats the one
1049
+ // thing the method exists for: resolving the fleet in a batch at
1050
+ // startup rather than paying per first-request. sekreto exposes no
1051
+ // batch `get`, so concurrency is the available shape.
1052
+ //
1053
+ // Names are deduped first: the broker's resolution cache is keyed
1054
+ // by SECRET NAME (§5.3), so several instances sharing one api-level
1055
+ // `secret` should cost one round-trip — and firing them together
1056
+ // would race past the cache and make several.
1057
+ const plan = [];
1058
+ const warmed = [];
1059
+ const missed = [];
1060
+ for (const name of wanted) {
1061
+ // THE REGISTRY IS THE AUTHORITY, and asking the profile instead
1062
+ // was wrong twice: an IMPERATIVE instance has no `profile.sdk`
1063
+ // block, so it was pushed to `missed` and never warmed at all —
1064
+ // and the re-derivation dropped the in-code `secret` feature
1065
+ // option, which beats the profile (§9). A registered instance
1066
+ // already carries the resolved name.
1067
+ // A NAME NOBODY DECLARED OR REGISTERED IS A MISS, not a lookup.
1068
+ // Widening the fallback to cover imperative instances also let a
1069
+ // typo — `stripe$prodd` — derive a secret name and call the
1070
+ // provider, so a nonexistent instance could be reported `warmed`
1071
+ // off a shared api-level credential. Registered OR declared, and
1072
+ // nothing else.
1073
+ const entry = this.registry.get(name);
1074
+ if (null == entry && null == this.profile.sdk[name]) {
1075
+ missed.push(name);
1076
+ continue;
1077
+ }
1078
+ const secretname = entry?.secretname ??
1079
+ (this.blockFor(name)?.secret ||
1080
+ (0, descriptor_1.secretnameDefault)(this.declaredRef(name)));
1081
+ plan.push({ name, secretname });
1082
+ }
1083
+ // One resolution per distinct secret name, awaited together; the
1084
+ // per-instance results are mapped back afterwards so the reported
1085
+ // shape is unchanged.
1086
+ const bysecret = new Map();
1087
+ for (const p of plan) {
1088
+ const at = bysecret.get(p.secretname);
1089
+ if (null == at) {
1090
+ bysecret.set(p.secretname, [p.name]);
1091
+ }
1092
+ else {
1093
+ at.push(p.name);
1094
+ }
1095
+ }
1096
+ const results = await Promise.all(Array.from(bysecret.entries()).map(async ([secretname, names]) => {
1097
+ try {
1098
+ await this.broker.value(names[0], secretname);
1099
+ return { names, ok: true };
1100
+ }
1101
+ catch (_e) {
1102
+ return { names, ok: false };
1103
+ }
1104
+ }));
1105
+ for (const r of results) {
1106
+ for (const n of r.names) {
1107
+ (r.ok ? warmed : missed).push(n);
1108
+ }
1109
+ }
1110
+ warmed.sort();
1111
+ missed.sort();
1112
+ return { warmed, missed };
1113
+ }
1114
+ // Every DECLARED instance (§6.1) - a different question from
1115
+ // `plugins()`, and the answers differ routinely: a lazily-started
1116
+ // instance is `active: true` and not yet live.
1117
+ instances() {
1118
+ const sdk = this.profile.sdk;
1119
+ return Object.keys(sdk).sort().map((name) => {
1120
+ const entry = this.registry.get(name);
1121
+ return {
1122
+ name,
1123
+ api: (0, profilecore_1.refapi)(name),
1124
+ // `active: false` means BARRED FROM RUNNING - a declaration that
1125
+ // stays in the file and here while being refused a client.
1126
+ active: false !== sdk[name].active,
1127
+ live: null != entry,
1128
+ rung: entry?.rung ?? 'none',
1129
+ block: sdk[name],
1130
+ };
1131
+ });
1132
+ }
1133
+ // §7.4: accepts an INSTANCE name and returns its api's descriptor -
1134
+ // one object shared by every instance of that api.
1135
+ descriptorOf(slug) {
1136
+ const entry = this.registry.get(slug);
1137
+ if (null == entry) {
1138
+ throw new error_1.StationError('station_no_plugin', 'unknown plugin "' + slug +
1139
+ '"; known: [' + Array.from(this.registry.keys()).join(', ') + ']');
1140
+ }
1141
+ return entry.descriptor;
1142
+ }
1143
+ canonicalDescriptor(slug) {
1144
+ return (0, descriptor_1.canonicalSerialize)(this.descriptorOf(slug));
1145
+ }
1146
+ events() {
1147
+ return this.buffer.events();
1148
+ }
1149
+ tap(fn) {
1150
+ return this.buffer.tap(fn);
1151
+ }
1152
+ status() {
1153
+ return {
1154
+ mode: 'solo',
1155
+ profile: this.profile.name,
1156
+ // §7.1: the registry is keyed by INSTANCE, so a status page that
1157
+ // projects only `slug` shows two indistinguishable rows for
1158
+ // `stripe$test` and `stripe$live` and omits the names it is keyed
1159
+ // by — an operator cannot tell which one is unhealthy. `slug`
1160
+ // stays for compatibility; `name` and `api` are what answer the
1161
+ // question.
1162
+ plugins: this.plugins().map((p) => ({
1163
+ name: p.name, api: p.api, slug: p.slug, rung: p.rung,
1164
+ })),
1165
+ events: this.buffer.status(),
1166
+ };
1167
+ }
1168
+ redact(text) {
1169
+ return this.broker.scrub(text);
1170
+ }
1171
+ refreshSecrets() {
1172
+ this.broker.refresh();
1173
+ }
1174
+ // close(): flush (solo: nothing in flight), then warn on profile
1175
+ // plugin keys that matched no registered plugin - a typo'd key
1176
+ // silently configuring nothing is the worst outcome for a
1177
+ // secrets-and-policy file (design §11).
1178
+ close() {
1179
+ if (this.closed) {
1180
+ return;
1181
+ }
1182
+ for (const slug of Object.keys(this.profile.sdk)) {
1183
+ if (!this.registry.has(slug)) {
1184
+ this.emit({
1185
+ t: Date.now(), kind: 'station',
1186
+ meta: {
1187
+ warn: 'profile plugin key "' + slug +
1188
+ '" matched no registered plugin',
1189
+ },
1190
+ });
1191
+ }
1192
+ }
1193
+ this.closed = true;
1194
+ if (Station.ambient === this) {
1195
+ Station.reset();
1196
+ }
1197
+ }
1198
+ emit(ev) {
1199
+ this.buffer.emit(ev);
1200
+ }
1201
+ }
1202
+ exports.Station = Station;
1203
+ Station.ambient = null;
1204
+ Station.ambientOpts = null;
1205
+ function firstNonEmpty(...vals) {
1206
+ for (const v of vals) {
1207
+ if (null != v && '' !== v) {
1208
+ return v;
1209
+ }
1210
+ }
1211
+ return undefined;
1212
+ }
1213
+ //# sourceMappingURL=Station.js.map