@crvouga/mockingbird-service-redis 2.4.0 → 2.6.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.
package/dist/cli.js CHANGED
@@ -18,9 +18,6 @@ import {
18
18
 
19
19
  // ../../adapters/node/dist/cli.js
20
20
  import { readFile as readFile5 } from "node:fs/promises";
21
- import { createRequire as createRequire3 } from "node:module";
22
- import { resolve as resolve3 } from "node:path";
23
- import { pathToFileURL } from "node:url";
24
21
  import { parseArgs } from "node:util";
25
22
 
26
23
  // ../../adapters/node/dist/fleet.js
@@ -34,6 +31,31 @@ import { createHash as createHash3, randomBytes, randomUUID as randomUUID3 } fro
34
31
 
35
32
  // ../../adapters/node/dist/fleet-archive.js
36
33
  import { createHash } from "node:crypto";
34
+ function validateCompatibilityTags(tags) {
35
+ if (!tags || typeof tags !== "object" || Array.isArray(tags))
36
+ throw new Error("invalid archive compatibility tags");
37
+ const entries = Object.entries(tags);
38
+ if (entries.length > 32 || entries.some(([key, value]) => !/^[A-Za-z0-9_.-]{1,64}$/.test(key) || typeof value !== "string" || value.length < 1 || value.length > 256 || [...value].some((character) => character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127)))
39
+ throw new Error("invalid archive compatibility tags");
40
+ }
41
+ function assertCompatibilityTags(tags, policy) {
42
+ if (tags !== void 0)
43
+ validateCompatibilityTags(tags);
44
+ if (!policy)
45
+ return;
46
+ validateCompatibilityTags(policy.tags);
47
+ if (policy.missing !== void 0 && !["allow", "reject"].includes(policy.missing))
48
+ throw new Error("invalid missing compatibility policy");
49
+ if (tags === void 0 && policy.missing === "allow")
50
+ return;
51
+ if (canonical(tags) !== canonical(policy.tags))
52
+ throw new Error("application archive compatibility mismatch");
53
+ }
54
+ function assertArchiveCompatibility(input, policy) {
55
+ const archive = validateArchive(input);
56
+ assertCompatibilityTags(archive.compatibility, policy);
57
+ return archive;
58
+ }
37
59
  var canonical = (value) => {
38
60
  if (Array.isArray(value))
39
61
  return `[${value.map(canonical).join(",")}]`;
@@ -53,6 +75,8 @@ function validateArchive(value) {
53
75
  const { sha256, ...content } = doc;
54
76
  if (doc.format !== "mockingbird.fleet/v1" || typeof doc.sourceId !== "string" || typeof doc.createdAt !== "string" || !doc.namespaces || typeof doc.namespaces !== "object" || Array.isArray(doc.namespaces) || sha256 !== digest(content))
55
77
  throw new Error("unsupported or corrupt fleet archive");
78
+ if (doc.compatibility !== void 0)
79
+ validateCompatibilityTags(doc.compatibility);
56
80
  for (const [namespace, entry] of Object.entries(doc.namespaces)) {
57
81
  if (!/^[A-Za-z0-9_.-]{1,64}$/.test(namespace) || !entry || !Number.isFinite(entry.clock?.now) || typeof entry.clock?.frozen !== "boolean" || !entry.services || !Object.keys(entry.services).length)
58
82
  throw new Error("invalid archive namespace");
@@ -68,6 +92,7 @@ function inspectArchive(input) {
68
92
  format: archive.format,
69
93
  createdAt: archive.createdAt,
70
94
  sha256: archive.sha256,
95
+ ...archive.compatibility ? { compatibility: archive.compatibility } : {},
71
96
  namespaces: Object.fromEntries(Object.entries(archive.namespaces).map(([name, ns]) => [
72
97
  name,
73
98
  {
@@ -710,11 +735,28 @@ var ingressSupport = {
710
735
  streaming: true,
711
736
  signing: "vendor request signing is not used; webhook signatures remain payload based"
712
737
  },
738
+ cognito: {
739
+ publicOrigin: true,
740
+ pathPrefix: true,
741
+ namespaces: "path-or-header",
742
+ streaming: true,
743
+ signing: "JWT issuer and JWKS use the configured public namespace; SigV4 verification is not modelled"
744
+ },
745
+ medplum: {
746
+ publicOrigin: true,
747
+ pathPrefix: true,
748
+ namespaces: "path-or-header",
749
+ streaming: true,
750
+ signing: "FHIR, OAuth and storage URLs use the configured public namespace"
751
+ },
713
752
  other: {
714
753
  publicOrigin: false,
715
754
  reason: "host/path-sensitive signing and hosted URL rewriting are not certified; use a direct endpoint"
716
755
  }
717
756
  };
757
+ function supportsPublicIngress(service) {
758
+ return service === "stripe" || service === "cognito" || service === "medplum";
759
+ }
718
760
  function advertisedHttpBase(entry) {
719
761
  if (entry.publicPath !== void 0 && !entry.publicOrigin)
720
762
  throw new Error("publicPath requires publicOrigin");
@@ -1253,7 +1295,7 @@ data: ${JSON.stringify(data)}
1253
1295
  {
1254
1296
  protocol: c.protocol,
1255
1297
  coverage: c.coverage,
1256
- ingress: c.targetName === "stripe" ? ingressSupport.stripe : ingressSupport.other,
1298
+ ingress: supportsPublicIngress(c.targetName ?? "") ? ingressSupport[c.targetName] : ingressSupport.other,
1257
1299
  target: c.targetName,
1258
1300
  outboundPolicy: c.outboundPolicy ?? "unsupported",
1259
1301
  version: 1,
@@ -2337,11 +2379,12 @@ data: ${JSON.stringify(data)}
2337
2379
  format: "mockingbird.fleet/v1",
2338
2380
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
2339
2381
  sourceId: this.ctx.id,
2382
+ ...this.ctx.options.archiveCompatibility ? { compatibility: structuredClone(this.ctx.options.archiveCompatibility.tags) } : {},
2340
2383
  namespaces: contents
2341
2384
  });
2342
2385
  }
2343
2386
  async restoreArchive(input, selectedNamespace) {
2344
- const archive = validateArchive(input);
2387
+ const archive = assertArchiveCompatibility(input, this.ctx.options.archiveCompatibility);
2345
2388
  const entries = Object.entries(archive.namespaces).filter(([ns]) => selectedNamespace === void 0 || ns === selectedNamespace);
2346
2389
  if (!entries.length)
2347
2390
  throw new Error("selected namespace absent from archive");
@@ -2925,7 +2968,7 @@ async function preflightFleet(config, options) {
2925
2968
  if (entry.target !== void 0 && !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(entry.target))
2926
2969
  throw new Error("target must name a supported service suffix");
2927
2970
  const service = entry.target ?? name;
2928
- if (advertisedHttpBase(entry) && service !== "stripe")
2971
+ if (advertisedHttpBase(entry) && !supportsPublicIngress(service))
2929
2972
  throw new Error(`public ingress unsupported for ${service}; use a direct endpoint to preserve signed targets`);
2930
2973
  const target = await options.load(service);
2931
2974
  const protocol = "protocol" in target ? target.protocol : "http";
@@ -2976,7 +3019,7 @@ async function preflightFleet(config, options) {
2976
3019
  break;
2977
3020
  }
2978
3021
  }
2979
- targets.set(name, { ...target, packageVersion: packageVersion ?? "2.4.0" });
3022
+ targets.set(name, { ...target, packageVersion: packageVersion ?? "2.6.0" });
2980
3023
  } catch (error) {
2981
3024
  throw new Error(`service ${name}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
2982
3025
  }
@@ -3020,6 +3063,11 @@ async function preflightFleet(config, options) {
3020
3063
  return ordered;
3021
3064
  }
3022
3065
  function validateFleetPolicies(options) {
3066
+ if (options.archiveCompatibility) {
3067
+ validateCompatibilityTags(options.archiveCompatibility.tags);
3068
+ if (options.archiveCompatibility.missing !== void 0 && !["allow", "reject"].includes(options.archiveCompatibility.missing))
3069
+ throw new Error("archiveCompatibility.missing must be allow or reject");
3070
+ }
3023
3071
  if (options.journal && !options.repository)
3024
3072
  throw new Error("durable operation journal requires an archive repository");
3025
3073
  if (options.cors) {
@@ -4012,10 +4060,44 @@ async function startFleet(config, options) {
4012
4060
  }
4013
4061
  }
4014
4062
 
4015
- // ../../adapters/node/dist/fleet-tools.js
4016
- import { readFile as readFile4 } from "node:fs/promises";
4063
+ // ../../adapters/node/dist/fleet-loader.js
4017
4064
  import { createRequire as createRequire2 } from "node:module";
4018
4065
  import { resolve as resolve2 } from "node:path";
4066
+ import { pathToFileURL } from "node:url";
4067
+ var suffix = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
4068
+ function createInstalledServiceLoader(options) {
4069
+ if (!options.projectRoot)
4070
+ throw new Error("consumer projectRoot required");
4071
+ const allowed = new Set(options.services);
4072
+ for (const name of allowed)
4073
+ if (!suffix.test(name))
4074
+ throw new Error("invalid service suffix");
4075
+ const require2 = createRequire2(resolve2(options.projectRoot, "package.json"));
4076
+ const targets = new Map((options.targets ?? []).map((target) => [target.name, target]));
4077
+ return async (name) => {
4078
+ if (!suffix.test(name) || !allowed.has(name))
4079
+ throw new Error("service is not declared in loader allowlist");
4080
+ const own = targets.get(name);
4081
+ if (own)
4082
+ return own;
4083
+ const specifier = `@crvouga/mockingbird-service-${name}/server`;
4084
+ let location;
4085
+ try {
4086
+ location = require2.resolve(specifier);
4087
+ } catch {
4088
+ throw new Error(`cannot load service "${name}": install @crvouga/mockingbird-service-${name} in the consumer project; its /server export is required`);
4089
+ }
4090
+ const mod = await import(pathToFileURL(location).href);
4091
+ if (!mod.serveTarget || mod.serveTarget.name !== name || ("protocol" in mod.serveTarget ? typeof mod.serveTarget.start !== "function" : typeof mod.serveTarget.create !== "function"))
4092
+ throw new Error(`${specifier} exports no matching serveTarget`);
4093
+ return mod.serveTarget;
4094
+ };
4095
+ }
4096
+
4097
+ // ../../adapters/node/dist/fleet-tools.js
4098
+ import { readFile as readFile4 } from "node:fs/promises";
4099
+ import { createRequire as createRequire3 } from "node:module";
4100
+ import { resolve as resolve3 } from "node:path";
4019
4101
 
4020
4102
  // ../../adapters/node/dist/fleet-client.js
4021
4103
  import { randomUUID as randomUUID5 } from "node:crypto";
@@ -4029,6 +4111,14 @@ var FleetClientError = class extends Error {
4029
4111
  this.details = details;
4030
4112
  }
4031
4113
  };
4114
+ var FleetClientResponseError = class extends FleetClientError {
4115
+ code;
4116
+ constructor(code, status, origin) {
4117
+ super(status, { code, body: "omitted", ...origin ? { origin } : {} });
4118
+ this.code = code;
4119
+ this.name = "FleetClientResponseError";
4120
+ }
4121
+ };
4032
4122
  var FleetClient = class {
4033
4123
  base;
4034
4124
  options;
@@ -4041,7 +4131,14 @@ var FleetClient = class {
4041
4131
  if (url.username || url.password)
4042
4132
  throw new Error("fleet client URL must not contain credentials");
4043
4133
  url.searchParams.set("namespace", options.namespace ?? this.options.namespace ?? "default");
4134
+ const limit = options.maxResponseBytes ?? this.options.maxResponseBytes ?? 64 * 1024 * 1024;
4135
+ if (!Number.isSafeInteger(limit) || limit < 1)
4136
+ throw new Error("invalid response byte limit");
4137
+ const deadline = AbortSignal.timeout(this.options.timeoutMs ?? 3e4);
4138
+ const signal = options.signal ? AbortSignal.any([options.signal, deadline]) : deadline;
4139
+ signal.throwIfAborted();
4044
4140
  const response = await (this.options.fetch ?? fetch)(url, {
4141
+ redirect: "manual",
4045
4142
  method: options.method ?? (options.body === void 0 ? "GET" : "POST"),
4046
4143
  headers: {
4047
4144
  "content-type": "application/json",
@@ -4049,11 +4146,71 @@ var FleetClient = class {
4049
4146
  ...options.idempotencyKey ? { "idempotency-key": options.idempotencyKey } : {}
4050
4147
  },
4051
4148
  ...options.body !== void 0 ? { body: JSON.stringify(options.body) } : {},
4052
- signal: options.signal ?? AbortSignal.timeout(this.options.timeoutMs ?? 3e4)
4149
+ signal
4053
4150
  });
4054
- const data = await response.json();
4055
- if (!response.ok)
4056
- throw new FleetClientError(response.status, data);
4151
+ if (response.status >= 300 && response.status < 400) {
4152
+ await response.body?.cancel();
4153
+ throw new FleetClientResponseError("redirect", response.status, url.origin);
4154
+ }
4155
+ if (Number(response.headers.get("content-length")) > limit) {
4156
+ await response.body?.cancel();
4157
+ throw new FleetClientResponseError("response_too_large", response.status);
4158
+ }
4159
+ const reader = response.body?.getReader();
4160
+ const chunks = [];
4161
+ let size = 0;
4162
+ const abort = () => {
4163
+ void reader?.cancel(signal.reason).catch(() => {
4164
+ });
4165
+ };
4166
+ signal.addEventListener("abort", abort, { once: true });
4167
+ try {
4168
+ if (reader)
4169
+ while (true) {
4170
+ signal.throwIfAborted();
4171
+ const { done, value } = await reader.read();
4172
+ signal.throwIfAborted();
4173
+ if (done)
4174
+ break;
4175
+ size += value.byteLength;
4176
+ if (size > limit) {
4177
+ await reader.cancel();
4178
+ throw new FleetClientResponseError("response_too_large", response.status);
4179
+ }
4180
+ chunks.push(value);
4181
+ }
4182
+ } finally {
4183
+ signal.removeEventListener("abort", abort);
4184
+ if (signal.aborted)
4185
+ await reader?.cancel(signal.reason).catch(() => {
4186
+ });
4187
+ reader?.releaseLock();
4188
+ }
4189
+ const bytes = new Uint8Array(size);
4190
+ let offset = 0;
4191
+ for (const chunk of chunks) {
4192
+ bytes.set(chunk, offset);
4193
+ offset += chunk.byteLength;
4194
+ }
4195
+ const text = new TextDecoder().decode(bytes);
4196
+ let data;
4197
+ try {
4198
+ data = text.length ? JSON.parse(text) : void 0;
4199
+ } catch {
4200
+ if (response.ok)
4201
+ throw new FleetClientResponseError("invalid_json", response.status);
4202
+ }
4203
+ if (!response.ok) {
4204
+ const error = data && typeof data === "object" ? data.error : void 0;
4205
+ const detail = { body: "omitted" };
4206
+ if (error && typeof error === "object")
4207
+ for (const key of ["type", "code"]) {
4208
+ const value = error[key];
4209
+ if (typeof value === "string" && /^[A-Za-z0-9_.-]{1,128}$/.test(value))
4210
+ detail[key] = value;
4211
+ }
4212
+ throw new FleetClientError(response.status, detail);
4213
+ }
4057
4214
  return data;
4058
4215
  }
4059
4216
  discover() {
@@ -4119,17 +4276,52 @@ function renderConnections(manifest, privateManifest, namespace, mapping) {
4119
4276
  const child = manifest.services[entry.service], secret = privateManifest.services[entry.service];
4120
4277
  if (!child || !secret)
4121
4278
  throw new Error(`missing service mapping ${entry.service}`);
4279
+ let endpoint;
4122
4280
  if (child.protocol === "http") {
4123
4281
  const template = child.namespaces.path;
4124
4282
  if (typeof template !== "string")
4125
4283
  throw new Error(`missing HTTP namespace mapping ${entry.service}`);
4126
- result[variable] = new URL(template.replace("{name}", encodeURIComponent(namespace)), secret.url).href;
4284
+ endpoint = new URL(template.replace("{name}", encodeURIComponent(namespace)), secret.url).href;
4127
4285
  } else {
4128
- const endpoint = secret.namespaces?.[namespace];
4129
- if (!endpoint)
4286
+ const selected = secret.namespaces?.[namespace];
4287
+ if (!selected)
4130
4288
  throw new Error(`missing namespace mapping ${namespace}/${entry.service}`);
4131
- result[variable] = endpoint;
4289
+ endpoint = selected;
4132
4290
  }
4291
+ const url = new URL(endpoint);
4292
+ const field = entry.field ?? "url";
4293
+ let value;
4294
+ switch (field) {
4295
+ case "url":
4296
+ value = endpoint;
4297
+ break;
4298
+ case "hostname":
4299
+ value = url.hostname.replace(/^\[|\]$/g, "");
4300
+ break;
4301
+ case "port":
4302
+ value = url.port;
4303
+ break;
4304
+ case "username":
4305
+ value = decodeURIComponent(url.username);
4306
+ break;
4307
+ case "password":
4308
+ value = decodeURIComponent(url.password);
4309
+ break;
4310
+ case "pathname":
4311
+ value = decodeURIComponent(url.pathname);
4312
+ break;
4313
+ case "database":
4314
+ value = decodeURIComponent(url.pathname.replace(/^\//, ""));
4315
+ break;
4316
+ default:
4317
+ throw new Error("unsupported connection field");
4318
+ }
4319
+ if (!value) {
4320
+ if (typeof entry.fallback !== "string")
4321
+ throw new Error(`missing connection component ${field}`);
4322
+ value = entry.fallback;
4323
+ }
4324
+ result[variable] = value;
4133
4325
  }
4134
4326
  return result;
4135
4327
  }
@@ -4153,7 +4345,7 @@ async function doctorFleet(config, options, probes = []) {
4153
4345
  const plan = [];
4154
4346
  try {
4155
4347
  const targets = await preflightFleet(config, options);
4156
- const require2 = createRequire2(resolve2(process.cwd(), "package.json"));
4348
+ const require2 = createRequire3(resolve3(process.cwd(), "package.json"));
4157
4349
  for (const [service, target] of targets) {
4158
4350
  let version = "development";
4159
4351
  try {
@@ -4208,7 +4400,7 @@ async function doctorFleet(config, options, probes = []) {
4208
4400
  };
4209
4401
  }
4210
4402
  async function rehearseFleet(config, options, input, probes = [], timeoutMs = 3e4) {
4211
- const archive = validateArchive(input);
4403
+ const archive = assertArchiveCompatibility(input, options.archiveCompatibility);
4212
4404
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
4213
4405
  const isolated = {
4214
4406
  ...config,
@@ -4220,7 +4412,7 @@ async function rehearseFleet(config, options, input, probes = [], timeoutMs = 3e
4220
4412
  };
4221
4413
  let fleet;
4222
4414
  try {
4223
- fleet = await startFleet(isolated, { load: options.load });
4415
+ fleet = await startFleet(isolated, options);
4224
4416
  const client = new FleetClient(fleet.manifest.adminBase, {
4225
4417
  ...config.adminKey ? { adminKey: config.adminKey } : {}
4226
4418
  });
@@ -4595,26 +4787,7 @@ var resolveServeControls = async (values, env = process.env, base) => {
4595
4787
  normalizeBootControls(document, "adminControls");
4596
4788
  return document;
4597
4789
  };
4598
- var loadTarget = async (name, own) => {
4599
- if (name === own.name)
4600
- return own;
4601
- const specifier = `@crvouga/mockingbird-service-${name}/server`;
4602
- try {
4603
- let mod;
4604
- try {
4605
- mod = await import(specifier);
4606
- } catch {
4607
- const fromProject = createRequire3(resolve3(process.cwd(), "package.json"));
4608
- mod = await import(pathToFileURL(fromProject.resolve(specifier)).href);
4609
- }
4610
- if (!mod.serveTarget)
4611
- throw new Error(`${specifier} exports no serveTarget`);
4612
- return mod.serveTarget;
4613
- } catch (error) {
4614
- const reason = error instanceof Error ? error.message : String(error);
4615
- throw new Error(`cannot load service "${name}": ${reason}. Install @crvouga/mockingbird-service-${name}.`);
4616
- }
4617
- };
4790
+ var loadTarget = (name, own) => createInstalledServiceLoader({ projectRoot: process.cwd(), services: [name], targets: [own] })(name);
4618
4791
  var start = async (target, values, config) => {
4619
4792
  const adminPrefix = resolveAdminPrefix(config.adminPrefix);
4620
4793
  const runtime = await target.create(values, {