@datafn/server 0.1.4-maint.0 → 0.2.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/index.js CHANGED
@@ -1,10 +1,11 @@
1
- import { validateSchema, ensureBuiltinTemporal, ensureBuiltinKv, isNamespaced, ensureBuiltinPublicLinks, hasTemporalGrouping, resolveCapabilities, normalizeDfql, buildSchemaIndex as buildSchemaIndex$1, getCapabilityFields, runBeforeHook, getTemporalGroupAliases, getTemporalClauses, parseSortTerm, endpointIncludes, runAfterHook, checkPrototypePollution, validateFieldValue, TIMEZONE_CHANGE_RESOURCE_NAME, createTimezoneResolver, normalizeTemporalQuery, evaluateFilter as evaluateFilter$1, findRelationMatch, endpointList, relationTargetEndpoint, sortRecords, relationKeyFor, getRelationJoinTableName, resolveEndpointResource, resourceNameFromId, normalizeRelationFkRecord, parseSelectToken, getJoinStoreKey, OP_REMAP, parseSortTerms as parseSortTerms$1, getTemporalGroups, resolveTemporalBucketValue, calculateAggregation, normalizeRelationPayload, relationFkFieldForManyOne, firstEndpoint, RELATION_CAPABILITY_FIELD_DEFS, coerceDateFieldsToEpoch } from '@datafn/core';
1
+ import { DATAFN_ROUTE_MAX_TTL_MS, validateDatafnRegionalEndpoint, DATAFN_ROUTE_TICKET_HEADER, DATAFN_ROUTE_WS_TICKET_PREFIX, DATAFN_ROUTE_WS_PROTOCOL, validateSchema, ensureBuiltinTemporal, ensureBuiltinKv, isNamespaced, ensureBuiltinPublicLinks, assertSupportedNamespaceStorageVersions, namespaceStorageManifestEntry, DATAFN_NAMESPACE_STORAGE_SCHEMA_VERSION, DATAFN_NAMESPACE_STORAGE_MANIFEST_VERSION, getAncestorInactiveResources, ANCESTOR_INACTIVE_FIELD, parseDatafnRequest, collectStructuralResourceSelectors, hasTemporalGrouping, resolveCapabilities, getCapabilityFields, getRelationJoinTableName, normalizeDfql, buildSchemaIndex as buildSchemaIndex$1, runBeforeHook, getTemporalGroupAliases, getTemporalClauses, parseSortTerm, endpointIncludes, runAfterHook, checkPrototypePollution, validateFieldValue, toBoundsEpochMs, formatBoundEpochMs, TIMEZONE_CHANGE_RESOURCE_NAME, createTimezoneResolver, normalizeTemporalQuery, relationFkFieldForManyOne, relationFkFieldForOneMany, resolveEndpointResource, endpointList, evaluateFilter as evaluateFilter$1, findRelationMatch, relationTargetEndpoint, sortRecords, relationKeyFor, resourceNameFromId, findSystemFieldWrite, normalizeRelationFkRecord, parseSelectToken, getJoinStoreKey, OP_REMAP, parseSortTerms as parseSortTerms$1, stripNullsForNonNullableFields, getTemporalGroups, resolveTemporalBucketValue, calculateAggregation, normalizeRelationPayload, firstEndpoint, RELATION_CAPABILITY_FIELD_DEFS, coerceDateFieldsToEpoch, resourceRequiresAncestorInactive } from '@datafn/core';
2
+ export { DATAFN_REQUEST_ACTIONS, DATAFN_REQUEST_PROTOCOL_VERSION, DATAFN_REQUEST_PROTOCOL_VERSIONS, DATAFN_STRUCTURAL_SELECTOR_POSITIONS, collectStructuralResourceSelectors, extractStructuralResourceSelectors, isDatafnRequestAction, parseDatafnRequest } from '@datafn/core';
2
3
  import { createRouter, createObservabilityMiddleware, executeMiddlewareChain } from '@superfunctions/http';
3
4
  import { wrapWithRowLevelNamespace, instrumentAdapter, instrumentKVStore } from '@superfunctions/db';
4
5
  import { normalizeObservability } from '@superfunctions/observability';
5
- import { createHash, createHmac, timingSafeEqual, randomUUID } from 'crypto';
6
+ import { timingSafeEqual, createPrivateKey, sign, createPublicKey, verify, randomUUID, createHash, createHmac } from 'crypto';
6
7
 
7
- // src/server.ts
8
+ // src/index.ts
8
9
 
9
10
  // src/execution/internal-tables.ts
10
11
  var META_COLUMNS = [
@@ -54,6 +55,9 @@ var INTERNAL_TABLE_SCHEMAS = {
54
55
  __datafn_seed: SEED_COLUMNS,
55
56
  __datafn_permission_directory_outbox: PERMISSION_DIRECTORY_OUTBOX_COLUMNS
56
57
  };
58
+ function listNamespacedInternalTables() {
59
+ return Object.entries(INTERNAL_TABLE_SCHEMAS).filter(([, columns]) => columns.some((column) => column.name === "namespace")).map(([name]) => name).sort();
60
+ }
57
61
  async function ensureInternalTable(adapter, tableName) {
58
62
  const columns = INTERNAL_TABLE_SCHEMAS[tableName];
59
63
  if (!columns) {
@@ -470,8 +474,8 @@ function createSequenceStore(config) {
470
474
  // src/http/json.ts
471
475
  async function parseJsonBody(req) {
472
476
  try {
473
- const text = await req.text();
474
- if (!text || text.trim() === "") {
477
+ const text2 = await req.text();
478
+ if (!text2 || text2.trim() === "") {
475
479
  return {
476
480
  ok: false,
477
481
  error: {
@@ -481,7 +485,7 @@ async function parseJsonBody(req) {
481
485
  }
482
486
  };
483
487
  }
484
- const data = JSON.parse(text);
488
+ const data = JSON.parse(text2);
485
489
  return { ok: true, data };
486
490
  } catch (error) {
487
491
  return {
@@ -731,6 +735,13 @@ function validateRecordKeys(index, resourceName, record, basePath, mode = "write
731
735
  for (const key of Object.keys(record)) {
732
736
  if (key === "id") continue;
733
737
  if (!fields.has(key)) {
738
+ if (mode === "write" && index.fieldsByResource.get(resourceName)?.has(key)) {
739
+ return vErr(
740
+ "DFQL_INVALID",
741
+ `Field is read-only: ${key} on ${resourceName}`,
742
+ `${basePath}.${key}`
743
+ );
744
+ }
734
745
  return vErr(
735
746
  "DFQL_UNKNOWN_FIELD",
736
747
  `Unknown field: ${key} on ${resourceName}`,
@@ -1019,13 +1030,32 @@ function validateMutation(mutation, index, basePath = "$", opts) {
1019
1030
  `${basePath}.record.${fieldName}`
1020
1031
  );
1021
1032
  }
1033
+ if (fieldDef.type === "date" && (fieldDef.min !== void 0 || fieldDef.max !== void 0)) {
1034
+ const epoch = toBoundsEpochMs(value);
1035
+ if (Number.isFinite(epoch)) {
1036
+ if (fieldDef.min !== void 0 && epoch < fieldDef.min) {
1037
+ return vErr(
1038
+ "DFQL_INVALID",
1039
+ `Field '${fieldName}' must be on or after ${formatBoundEpochMs(fieldDef.min)}`,
1040
+ `${basePath}.record.${fieldName}`
1041
+ );
1042
+ }
1043
+ if (fieldDef.max !== void 0 && epoch > fieldDef.max) {
1044
+ return vErr(
1045
+ "DFQL_INVALID",
1046
+ `Field '${fieldName}' must be on or before ${formatBoundEpochMs(fieldDef.max)}`,
1047
+ `${basePath}.record.${fieldName}`
1048
+ );
1049
+ }
1050
+ }
1051
+ }
1022
1052
  }
1023
1053
  if (m.operation === "insert" || m.operation === "replace") {
1024
1054
  const resource2 = resourceResult.result;
1025
1055
  const record2 = m.record;
1026
1056
  for (const field of resource2.fields) {
1027
1057
  if (field.required && field.default === void 0 && field.name !== "id" && !field.readonly) {
1028
- if (!(field.name in record2) || record2[field.name] === null || record2[field.name] === void 0) {
1058
+ if (!(field.name in record2) || record2[field.name] === void 0 || record2[field.name] === null && !field.nullable) {
1029
1059
  return vErr(
1030
1060
  "DFQL_INVALID",
1031
1061
  `Required field missing: ${field.name}`,
@@ -3273,6 +3303,22 @@ function filterAncestorInactiveRecords(records, match, metadata) {
3273
3303
  }
3274
3304
  return records.filter((record) => record.isAncestorInactive !== true);
3275
3305
  }
3306
+ function isPlainRecord(value) {
3307
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
3308
+ return false;
3309
+ }
3310
+ const prototype = Object.getPrototypeOf(value);
3311
+ return prototype === Object.prototype || prototype === null;
3312
+ }
3313
+ function applyOmitToArrayValue(value, omit) {
3314
+ if (Array.isArray(value)) {
3315
+ return value.map((item) => applyOmitToArrayValue(item, omit));
3316
+ }
3317
+ if (isPlainRecord(value)) {
3318
+ return applyOmit(value, omit);
3319
+ }
3320
+ return value;
3321
+ }
3276
3322
  function applyOmit(record, omit) {
3277
3323
  if (!omit || omit.length === 0) {
3278
3324
  return record;
@@ -3281,13 +3327,8 @@ function applyOmit(record, omit) {
3281
3327
  for (const [key, value] of Object.entries(record)) {
3282
3328
  if (key === "id" || !omit.includes(key)) {
3283
3329
  if (Array.isArray(value)) {
3284
- result[key] = value.map((item) => {
3285
- if (typeof item === "object" && item !== null) {
3286
- return applyOmit(item, omit);
3287
- }
3288
- return item;
3289
- });
3290
- } else if (typeof value === "object" && value !== null && key !== "$relation_metadata") {
3330
+ result[key] = value.map((item) => applyOmitToArrayValue(item, omit));
3331
+ } else if (isPlainRecord(value) && key !== "$relation_metadata") {
3291
3332
  result[key] = applyOmit(value, omit);
3292
3333
  } else {
3293
3334
  result[key] = value;
@@ -3388,6 +3429,7 @@ function getFkFieldsToOmit(schema, targetResource) {
3388
3429
  function materializeSelect(record, resource, select, schema, store, omit, metadata) {
3389
3430
  const resourceSchema = schema.resources.find((r) => r.name === resource);
3390
3431
  if (!resourceSchema) return { id: record.id };
3432
+ record = stripNullsForNonNullableFields(record, resourceSchema);
3391
3433
  const fkFieldsToOmit = getFkFieldsToOmit(schema, resource);
3392
3434
  const effectiveOmit = omit ? [...omit, ...Array.from(fkFieldsToOmit)] : Array.from(fkFieldsToOmit);
3393
3435
  if (!select || select.length === 0) {
@@ -3496,7 +3538,9 @@ function materializeSelect(record, resource, select, schema, store, omit, metada
3496
3538
  ),
3497
3539
  htreeRelation,
3498
3540
  metadata
3499
- ).map((c) => applyOmit(c, omit));
3541
+ ).map(
3542
+ (c) => applyOmit(stripNullsForNonNullableFields(c, resourceSchema), omit)
3543
+ );
3500
3544
  } else if (parsed.directive === "**") {
3501
3545
  result[parsed.baseName] = filterAncestorInactiveRecords(
3502
3546
  htreeChildren(
@@ -3508,7 +3552,9 @@ function materializeSelect(record, resource, select, schema, store, omit, metada
3508
3552
  ),
3509
3553
  htreeRelation,
3510
3554
  metadata
3511
- ).map((d) => applyOmit(d, omit));
3555
+ ).map(
3556
+ (d) => applyOmit(stripNullsForNonNullableFields(d, resourceSchema), omit)
3557
+ );
3512
3558
  }
3513
3559
  includedFields.add(parsed.baseName);
3514
3560
  } else if (parsed.baseName === "parent") {
@@ -3517,7 +3563,9 @@ function materializeSelect(record, resource, select, schema, store, omit, metada
3517
3563
  resource,
3518
3564
  htreeRelation.relation,
3519
3565
  store
3520
- ).map((a) => applyOmit(a, omit));
3566
+ ).map(
3567
+ (a) => applyOmit(stripNullsForNonNullableFields(a, resourceSchema), omit)
3568
+ );
3521
3569
  includedFields.add(parsed.baseName);
3522
3570
  }
3523
3571
  continue;
@@ -3813,8 +3861,10 @@ function executeAggregateQuery(query, records, schema, store, temporal) {
3813
3861
  }
3814
3862
  const aggregations = query.aggregations || {};
3815
3863
  let results = [];
3864
+ const samples = /* @__PURE__ */ new WeakMap();
3816
3865
  for (const [, groupRecords] of groups.entries()) {
3817
3866
  const row = {};
3867
+ samples.set(row, groupRecords[0]);
3818
3868
  groupBy.forEach((field) => {
3819
3869
  const sample = groupRecords[0];
3820
3870
  const val = resolveValue(
@@ -3825,7 +3875,9 @@ function executeAggregateQuery(query, records, schema, store, temporal) {
3825
3875
  query.resource,
3826
3876
  resourceSchema
3827
3877
  );
3828
- row[field] = val;
3878
+ if (val !== void 0) {
3879
+ row[field] = val;
3880
+ }
3829
3881
  });
3830
3882
  for (const group of temporalGroups) {
3831
3883
  row[group.alias] = resolveTemporalBucketValue(groupRecords[0], group);
@@ -3865,7 +3917,24 @@ function executeAggregateQuery(query, records, schema, store, temporal) {
3865
3917
  paginated.length = limit;
3866
3918
  }
3867
3919
  return {
3868
- groups: paginated,
3920
+ groups: paginated.map((row) => {
3921
+ const output = { ...row };
3922
+ for (const field of groupBy) {
3923
+ if (Object.prototype.hasOwnProperty.call(aggregations, field)) continue;
3924
+ if (output[field] === null && resolveValue(
3925
+ samples.get(row),
3926
+ field,
3927
+ schema,
3928
+ store,
3929
+ query.resource,
3930
+ resourceSchema,
3931
+ true
3932
+ ) === void 0) {
3933
+ delete output[field];
3934
+ }
3935
+ }
3936
+ return output;
3937
+ }),
3869
3938
  nextCursor
3870
3939
  };
3871
3940
  }
@@ -3894,9 +3963,10 @@ function orderGroupedResults(groups, sortTerms) {
3894
3963
  return 0;
3895
3964
  });
3896
3965
  }
3897
- function resolveValue(record, path, schema, store, resourceName, precomputedResource) {
3966
+ function resolveValue(record, path, schema, store, resourceName, precomputedResource, normalize = false) {
3898
3967
  if (!path.includes(".")) {
3899
- return record[path];
3968
+ const definition2 = precomputedResource?.fields.find((field) => field.name === path);
3969
+ return normalize && record[path] === null && definition2 && definition2.nullable !== true ? void 0 : record[path];
3900
3970
  }
3901
3971
  const parts = path.split(".");
3902
3972
  const resource = precomputedResource ?? schema.resources.find((r) => r.name === resourceName);
@@ -3934,7 +4004,8 @@ function resolveValue(record, path, schema, store, resourceName, precomputedReso
3934
4004
  }
3935
4005
  }
3936
4006
  const lastField = parts[parts.length - 1];
3937
- return currentRecord[lastField];
4007
+ const definition = schema.resources.find((entry) => entry.name === currentResource)?.fields.find((field) => field.name === lastField);
4008
+ return normalize && currentRecord[lastField] === null && definition && definition.nullable !== true ? void 0 : currentRecord[lastField];
3938
4009
  }
3939
4010
  var DFQL_TO_ADAPTER_OP = {
3940
4011
  // $-prefixed DFQL operators
@@ -5164,6 +5235,7 @@ async function pushdownCore(query, schema, db, namespace) {
5164
5235
  function projectFieldsPushdown(record, resource, schema, select, omit) {
5165
5236
  const resourceSchema = schema.resources.find((r) => r.name === resource);
5166
5237
  if (!resourceSchema) return { id: record.id };
5238
+ record = stripNullsForNonNullableFields(record, resourceSchema);
5167
5239
  const resolvedCapabilities = resolveCapabilities(
5168
5240
  schema.capabilities,
5169
5241
  resourceSchema.capabilities
@@ -5932,6 +6004,292 @@ var AuthResolverCache = class {
5932
6004
  function createAuthResolverCache() {
5933
6005
  return new AuthResolverCache();
5934
6006
  }
6007
+ var scopes = /* @__PURE__ */ new Set([
6008
+ "query",
6009
+ "search",
6010
+ "mutation",
6011
+ "transact",
6012
+ "seed",
6013
+ "clone",
6014
+ "pull",
6015
+ "push",
6016
+ "reconcile",
6017
+ "custom",
6018
+ "websocket"
6019
+ ]);
6020
+ var text = (value) => typeof value === "string" && value.trim().length > 0 && value.length <= 1024;
6021
+ function routeTicketError(code) {
6022
+ return new DatafnRoutingError({
6023
+ code,
6024
+ message: code,
6025
+ status: code === "DATAFN_ROUTE_RATE_LIMITED" ? 429 : code === "DATAFN_ROUTE_FORBIDDEN" ? 403 : 401,
6026
+ retryable: code === "DATAFN_ROUTE_TICKET_EXPIRED" || code === "DATAFN_ROUTE_RATE_LIMITED",
6027
+ executionStarted: false
6028
+ });
6029
+ }
6030
+ function assertClaims(value) {
6031
+ if (!value || value.version !== 1 || ![value.issuer, value.audience, value.subject, value.namespace, value.regionId, value.ticketId].every(text) || !Number.isSafeInteger(value.epoch) || value.epoch < 1 || ![value.issuedAt, value.notBefore, value.expiresAt].every(Number.isSafeInteger) || value.notBefore < value.issuedAt || value.notBefore >= value.expiresAt || value.expiresAt - value.issuedAt > DATAFN_ROUTE_MAX_TTL_MS || !Array.isArray(value.scopes) || value.scopes.length === 0 || value.scopes.some((scope) => !scopes.has(scope)) || new Set(value.scopes).size !== value.scopes.length || value.sessionBinding !== void 0 && !text(value.sessionBinding)) {
6032
+ throw routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6033
+ }
6034
+ }
6035
+ function createDatafnHmacRouteTickets(input) {
6036
+ const keys = new Map(Object.entries(input.keys).map(([id, key]) => {
6037
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(id) || Buffer.byteLength(key) < 32) {
6038
+ throw new Error("DATAFN_ROUTE_KEY_INVALID");
6039
+ }
6040
+ return [id, Buffer.from(key)];
6041
+ }));
6042
+ if (!keys.has(input.activeKeyId)) throw new Error("DATAFN_ROUTE_ACTIVE_KEY_MISSING");
6043
+ const signature = (content, key) => createHmac("sha256", key).update(`datafn-regional-route-v1:${content}`).digest();
6044
+ return {
6045
+ sign(claims) {
6046
+ assertClaims(claims);
6047
+ const header = Buffer.from(JSON.stringify({ typ: "datafn-route-v1", alg: "HS256", kid: input.activeKeyId })).toString("base64url");
6048
+ const payload = Buffer.from(JSON.stringify(claims)).toString("base64url");
6049
+ const content = `${header}.${payload}`;
6050
+ return `${content}.${signature(content, keys.get(input.activeKeyId)).toString("base64url")}`;
6051
+ },
6052
+ verify(ticket) {
6053
+ try {
6054
+ if (typeof ticket !== "string" || ticket.length > 16384 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(ticket)) throw new Error();
6055
+ const [header, payload, mac] = ticket.split(".");
6056
+ const protectedHeader = JSON.parse(Buffer.from(header, "base64url").toString());
6057
+ const key = keys.get(protectedHeader.kid);
6058
+ if (!key || protectedHeader.typ !== "datafn-route-v1" || protectedHeader.alg !== "HS256") throw new Error();
6059
+ const expected = signature(`${header}.${payload}`, key);
6060
+ const actual = Buffer.from(mac, "base64url");
6061
+ if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) throw new Error();
6062
+ const claims = JSON.parse(Buffer.from(payload, "base64url").toString());
6063
+ assertClaims(claims);
6064
+ return claims;
6065
+ } catch {
6066
+ throw routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6067
+ }
6068
+ }
6069
+ };
6070
+ }
6071
+ var routeKeyId = (value) => /^[A-Za-z0-9_-]{1,128}$/.test(value);
6072
+ var routeSigningInput = (content) => Buffer.from(`datafn-regional-route-v1:${content}`);
6073
+ function createDatafnEd25519RouteTicketSigner(input) {
6074
+ if (!routeKeyId(input.activeKeyId)) throw new Error("DATAFN_ROUTE_KEY_INVALID");
6075
+ let key;
6076
+ try {
6077
+ key = typeof input.privateKey === "string" ? createPrivateKey(input.privateKey) : input.privateKey;
6078
+ } catch {
6079
+ throw new Error("DATAFN_ROUTE_KEY_INVALID");
6080
+ }
6081
+ if (key.type !== "private" || key.asymmetricKeyType !== "ed25519") throw new Error("DATAFN_ROUTE_KEY_INVALID");
6082
+ return {
6083
+ sign(claims) {
6084
+ assertClaims(claims);
6085
+ const header = Buffer.from(JSON.stringify({ typ: "datafn-route-v1", alg: "EdDSA", kid: input.activeKeyId })).toString("base64url");
6086
+ const payload = Buffer.from(JSON.stringify(claims)).toString("base64url");
6087
+ const content = `${header}.${payload}`;
6088
+ return `${content}.${sign(null, routeSigningInput(content), key).toString("base64url")}`;
6089
+ }
6090
+ };
6091
+ }
6092
+ function createDatafnEd25519RouteTicketVerifier(input) {
6093
+ const keys = new Map(Object.entries(input.publicKeys).map(([id, value]) => {
6094
+ if (!routeKeyId(id)) throw new Error("DATAFN_ROUTE_KEY_INVALID");
6095
+ if (typeof value === "string" && !value.startsWith("-----BEGIN PUBLIC KEY-----")) {
6096
+ throw new Error("DATAFN_ROUTE_KEY_INVALID");
6097
+ }
6098
+ let key;
6099
+ try {
6100
+ key = typeof value === "string" ? createPublicKey(value) : value;
6101
+ } catch {
6102
+ throw new Error("DATAFN_ROUTE_KEY_INVALID");
6103
+ }
6104
+ if (key.type !== "public" || key.asymmetricKeyType !== "ed25519") throw new Error("DATAFN_ROUTE_KEY_INVALID");
6105
+ return [id, key];
6106
+ }));
6107
+ if (keys.size === 0) throw new Error("DATAFN_ROUTE_KEY_INVALID");
6108
+ return {
6109
+ verify(ticket) {
6110
+ try {
6111
+ if (typeof ticket !== "string" || ticket.length > 16384 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(ticket)) throw new Error();
6112
+ const [header, payload, signature] = ticket.split(".");
6113
+ const protectedHeader = JSON.parse(Buffer.from(header, "base64url").toString());
6114
+ const key = keys.get(protectedHeader.kid);
6115
+ if (!key || protectedHeader.typ !== "datafn-route-v1" || protectedHeader.alg !== "EdDSA") throw new Error();
6116
+ if (!verify(null, routeSigningInput(`${header}.${payload}`), key, Buffer.from(signature, "base64url"))) throw new Error();
6117
+ const claims = JSON.parse(Buffer.from(payload, "base64url").toString());
6118
+ assertClaims(claims);
6119
+ return claims;
6120
+ } catch {
6121
+ throw routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6122
+ }
6123
+ }
6124
+ };
6125
+ }
6126
+ function createDatafnRouteBootstrap(config) {
6127
+ const ttl = config.ttlMs ?? 6e4;
6128
+ if (!text(config.issuer) || !Number.isSafeInteger(ttl) || ttl < 1e3 || ttl > DATAFN_ROUTE_MAX_TTL_MS) {
6129
+ throw new Error("DATAFN_ROUTE_BOOTSTRAP_CONFIG_INVALID");
6130
+ }
6131
+ const now = config.now ?? Date.now;
6132
+ return async (request) => {
6133
+ try {
6134
+ if (request.method !== "POST") return new Response(null, { status: 405, headers: { allow: "POST", "cache-control": "no-store" } });
6135
+ const identity = await config.authenticate(request);
6136
+ if (!identity || !text(identity.subject) || !text(identity.namespace)) throw routeTicketError("DATAFN_ROUTE_FORBIDDEN");
6137
+ let placement;
6138
+ try {
6139
+ placement = await config.directory.get(identity.namespace);
6140
+ } catch {
6141
+ throw new DatafnRoutingError({ code: "DATAFN_PLACEMENT_UNAVAILABLE", message: "Placement unavailable", status: 503, retryable: true });
6142
+ }
6143
+ if (!placement || placement.namespace !== identity.namespace || placement.state === "tombstoned") {
6144
+ throw new DatafnRoutingError({ code: "DATAFN_PLACEMENT_NOT_FOUND", message: "Placement not found", status: 404, retryable: false });
6145
+ }
6146
+ if (placement.state !== "active" || placement.migration) {
6147
+ throw new DatafnRoutingError({ code: "DATAFN_NAMESPACE_MOVING", message: "Placement is fenced", status: 409, retryable: true });
6148
+ }
6149
+ const permitted = [...await config.authorize(identity)];
6150
+ const endpoint = await config.resolveEndpoint(placement);
6151
+ const issuedAt = now();
6152
+ const expiresAt = Math.min(issuedAt + ttl, identity.expiresAt ?? Infinity);
6153
+ if (!Number.isSafeInteger(expiresAt) || expiresAt <= issuedAt) throw routeTicketError("DATAFN_ROUTE_FORBIDDEN");
6154
+ const httpUrl = validateDatafnRegionalEndpoint(endpoint.httpUrl);
6155
+ const wsUrl = endpoint.wsUrl ? validateDatafnRegionalEndpoint(endpoint.wsUrl, true) : void 0;
6156
+ if (permitted.includes("websocket") && !wsUrl) throw routeTicketError("DATAFN_ROUTE_FORBIDDEN");
6157
+ const ticket = await config.signer.sign({
6158
+ version: 1,
6159
+ issuer: config.issuer,
6160
+ audience: endpoint.audience,
6161
+ subject: identity.subject,
6162
+ namespace: identity.namespace,
6163
+ regionId: placement.regionId,
6164
+ epoch: placement.epoch,
6165
+ scopes: permitted,
6166
+ issuedAt,
6167
+ notBefore: issuedAt,
6168
+ expiresAt,
6169
+ ticketId: randomUUID(),
6170
+ ...identity.sessionBinding ? { sessionBinding: identity.sessionBinding } : {}
6171
+ });
6172
+ const descriptor = {
6173
+ version: 1,
6174
+ httpUrl,
6175
+ ...wsUrl ? { wsUrl } : {},
6176
+ ticket,
6177
+ expiresAt,
6178
+ renewAfter: issuedAt + Math.floor((expiresAt - issuedAt) * 0.8)
6179
+ };
6180
+ emit(config, { type: "issued" });
6181
+ return Response.json(descriptor, { headers: { "cache-control": "no-store", pragma: "no-cache" } });
6182
+ } catch (error) {
6183
+ emit(config, { type: "rejected", code: error instanceof DatafnRoutingError ? error.code : "DATAFN_ROUTE_FORBIDDEN" });
6184
+ return (error instanceof DatafnRoutingError ? error : routeTicketError("DATAFN_ROUTE_FORBIDDEN")).toResponse();
6185
+ }
6186
+ };
6187
+ }
6188
+ function readDatafnRouteTicket(request, websocket = false) {
6189
+ const header = request.headers.get(DATAFN_ROUTE_TICKET_HEADER);
6190
+ const protocols = (request.headers.get("sec-websocket-protocol") ?? "").split(",").map((s) => s.trim()).filter(Boolean);
6191
+ const tickets = protocols.filter((s) => s.startsWith(DATAFN_ROUTE_WS_TICKET_PREFIX));
6192
+ if (tickets.length > 1 || header && tickets.length || !websocket && tickets.length || tickets.length && !protocols.includes(DATAFN_ROUTE_WS_PROTOCOL)) throw routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6193
+ return header ?? tickets[0]?.slice(DATAFN_ROUTE_WS_TICKET_PREFIX.length);
6194
+ }
6195
+ async function verifyDatafnRegionalTicketIdentity(input) {
6196
+ const { request, regionId, runtime } = input;
6197
+ try {
6198
+ const origin = request.headers.get("origin");
6199
+ if (origin && !runtime.allowedOrigins?.includes(origin)) throw routeTicketError("DATAFN_ROUTE_FORBIDDEN");
6200
+ if (!runtime.authenticate && request.headers.has("cookie")) throw routeTicketError("DATAFN_ROUTE_FORBIDDEN");
6201
+ const token = readDatafnRouteTicket(request, input.websocket);
6202
+ if (!token) throw routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6203
+ const claims = await runtime.verifier.verify(token);
6204
+ assertClaims(claims);
6205
+ const now = (runtime.now ?? Date.now)();
6206
+ const skew = runtime.clockSkewMs ?? 5e3;
6207
+ if (!Number.isFinite(skew) || skew < 0 || skew > 3e4) throw routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6208
+ if (claims.expiresAt <= now) throw routeTicketError("DATAFN_ROUTE_TICKET_EXPIRED");
6209
+ if (claims.issuedAt > now + skew || claims.notBefore > now + skew || claims.issuer !== runtime.issuer || claims.audience !== runtime.audience || claims.regionId !== regionId) throw routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6210
+ return claims;
6211
+ } catch (error) {
6212
+ const safe = error instanceof DatafnRoutingError ? error : routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6213
+ emit(runtime, { type: "rejected", code: safe.code });
6214
+ throw safe;
6215
+ }
6216
+ }
6217
+ async function validateDatafnRouteTicket(input) {
6218
+ const { runtime } = input;
6219
+ const claims = await verifyDatafnRegionalTicketIdentity({
6220
+ request: input.request,
6221
+ regionId: input.regionId,
6222
+ runtime,
6223
+ websocket: input.scope === "websocket"
6224
+ });
6225
+ try {
6226
+ if (claims.namespace !== input.namespace || !claims.scopes.includes(input.scope)) {
6227
+ throw routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6228
+ }
6229
+ let identity;
6230
+ if (runtime.authenticate) {
6231
+ identity = await runtime.authenticate(input.request);
6232
+ if (!identity || identity.subject !== claims.subject || identity.namespace !== claims.namespace || identity.sessionBinding !== claims.sessionBinding || identity.expiresAt !== void 0 && (!Number.isFinite(identity.expiresAt) || identity.expiresAt <= (runtime.now ?? Date.now)())) {
6233
+ throw routeTicketError("DATAFN_ROUTE_FORBIDDEN");
6234
+ }
6235
+ if (identity.expiresAt !== void 0 && claims.expiresAt > identity.expiresAt) throw routeTicketError("DATAFN_ROUTE_TICKET_EXPIRED");
6236
+ }
6237
+ if (runtime.isActive && !await runtime.isActive(claims)) throw routeTicketError("DATAFN_ROUTE_TICKET_REVOKED");
6238
+ if (runtime.allowRequest && !await runtime.allowRequest(claims)) throw routeTicketError("DATAFN_ROUTE_RATE_LIMITED");
6239
+ const admittedAt = (runtime.now ?? Date.now)();
6240
+ if (identity?.expiresAt !== void 0 && identity.expiresAt <= admittedAt) throw routeTicketError("DATAFN_ROUTE_FORBIDDEN");
6241
+ if (claims.expiresAt <= admittedAt) throw routeTicketError("DATAFN_ROUTE_TICKET_EXPIRED");
6242
+ emit(runtime, { type: "accepted" });
6243
+ return claims;
6244
+ } catch (error) {
6245
+ const safe = error instanceof DatafnRoutingError ? error : routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6246
+ emit(runtime, { type: "rejected", code: safe.code });
6247
+ throw safe;
6248
+ }
6249
+ }
6250
+ function withDatafnRegionalCors(handler, options) {
6251
+ const origins = new Set(options.origins.map((origin) => {
6252
+ if (new URL(origin).origin !== origin || origin === "null") throw new Error("DATAFN_ROUTE_ORIGIN_INVALID");
6253
+ return origin;
6254
+ }));
6255
+ const allowedHeaders = /* @__PURE__ */ new Set([
6256
+ "content-type",
6257
+ "authorization",
6258
+ DATAFN_ROUTE_TICKET_HEADER,
6259
+ ...(options.headers ?? []).map((header) => header.toLowerCase())
6260
+ ]);
6261
+ const allowedMethods = ["GET", "POST", "PATCH", "DELETE"];
6262
+ return async (request) => {
6263
+ const origin = request.headers.get("origin");
6264
+ if (origin && !origins.has(origin)) return routeTicketError("DATAFN_ROUTE_FORBIDDEN").toResponse();
6265
+ if (request.headers.has("cookie")) return routeTicketError("DATAFN_ROUTE_FORBIDDEN").toResponse();
6266
+ if (request.method === "OPTIONS") {
6267
+ const method = request.headers.get("access-control-request-method");
6268
+ const headers2 = (request.headers.get("access-control-request-headers") ?? "").split(",").map((s) => s.trim().toLowerCase()).filter(Boolean);
6269
+ if (!origin || !allowedMethods.includes(method ?? "") || headers2.some((h) => !allowedHeaders.has(h))) return new Response(null, { status: 403 });
6270
+ return new Response(null, { status: 204, headers: {
6271
+ "access-control-allow-origin": origin,
6272
+ "access-control-allow-methods": allowedMethods.join(", "),
6273
+ "access-control-allow-headers": [...allowedHeaders].join(", "),
6274
+ vary: "Origin, Access-Control-Request-Method, Access-Control-Request-Headers",
6275
+ "cache-control": "no-store"
6276
+ } });
6277
+ }
6278
+ const response = await handler(request);
6279
+ const headers = new Headers(response.headers);
6280
+ headers.append("vary", "Origin");
6281
+ headers.delete("access-control-allow-credentials");
6282
+ headers.set("cache-control", "no-store");
6283
+ if (origin) headers.set("access-control-allow-origin", origin);
6284
+ return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
6285
+ };
6286
+ }
6287
+ function emit(config, event) {
6288
+ try {
6289
+ config.onEvent?.(event);
6290
+ } catch {
6291
+ }
6292
+ }
5935
6293
  var DATAFN_ROUTING_ASSERTION_HEADER = "x-datafn-routing-assertion";
5936
6294
  var DATAFN_ROUTING_INTERNAL_HEADERS = [
5937
6295
  DATAFN_ROUTING_ASSERTION_HEADER,
@@ -5946,9 +6304,13 @@ var DEFAULT_MIGRATION_RECOVERY_LEASE_MS = 3e4;
5946
6304
  var DatafnRoutingError = class extends Error {
5947
6305
  constructor(input) {
5948
6306
  super(input.message);
6307
+ /** HTTP-shaped metadata so framework routers map an uncaught routing error to its status
6308
+ * (e.g. a ticket-only context provider rejection) instead of a generic 500. */
6309
+ this.isHttpError = true;
5949
6310
  this.name = "DatafnRoutingError";
5950
6311
  this.code = input.code;
5951
6312
  this.status = input.status;
6313
+ this.statusCode = input.status;
5952
6314
  this.retryable = input.retryable;
5953
6315
  this.executionStarted = input.executionStarted ?? false;
5954
6316
  this.placement = input.placement;
@@ -6083,6 +6445,28 @@ async function claimDatafnNamespacePlacement(input) {
6083
6445
  async function validateDatafnPlacement(input) {
6084
6446
  const startedAt = Date.now();
6085
6447
  const requestId2 = input.request?.headers.get("x-request-id") ?? void 0;
6448
+ let ticket;
6449
+ const hasAssertion = Boolean(input.request?.headers.get(input.runtime.assertionHeader ?? DATAFN_ROUTING_ASSERTION_HEADER)?.trim());
6450
+ if (input.request) {
6451
+ const token = readDatafnRouteTicket(input.request, input.scope === "websocket");
6452
+ if (token !== void 0 && (hasAssertion || !input.runtime.routeTickets)) {
6453
+ throw routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6454
+ }
6455
+ if (input.runtime.routeTickets && (!hasAssertion || token !== void 0)) {
6456
+ if (DATAFN_ROUTING_INTERNAL_HEADERS.some((name) => input.request.headers.has(name))) {
6457
+ throw routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6458
+ }
6459
+ ticket = await validateDatafnRouteTicket({
6460
+ request: input.request,
6461
+ namespace: input.namespace,
6462
+ regionId: input.regionId,
6463
+ scope: input.scope ?? "custom",
6464
+ runtime: input.runtime.routeTickets
6465
+ });
6466
+ }
6467
+ } else if (input.runtime.routeTickets && !input.trustedInternal) {
6468
+ throw routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6469
+ }
6086
6470
  let placement;
6087
6471
  try {
6088
6472
  placement = await input.runtime.directory.get(input.namespace);
@@ -6120,7 +6504,7 @@ async function validateDatafnPlacement(input) {
6120
6504
  retryable: false
6121
6505
  });
6122
6506
  }
6123
- const assertion = await validateRoutingAssertion({
6507
+ const assertion = ticket ? void 0 : await validateRoutingAssertion({
6124
6508
  namespace: input.namespace,
6125
6509
  regionId: input.regionId,
6126
6510
  placement,
@@ -6176,7 +6560,7 @@ async function validateDatafnPlacement(input) {
6176
6560
  internal: Boolean(assertion)
6177
6561
  });
6178
6562
  }
6179
- if (assertion && assertion.epoch !== placement.epoch) {
6563
+ if (assertion && assertion.epoch !== placement.epoch || ticket && ticket.epoch !== placement.epoch) {
6180
6564
  await emitRoutingEvent(input.runtime, {
6181
6565
  type: "mismatch",
6182
6566
  requestId: requestId2,
@@ -6189,14 +6573,17 @@ async function validateDatafnPlacement(input) {
6189
6573
  });
6190
6574
  throw new DatafnRoutingError({
6191
6575
  code: "DATAFN_REGION_MISMATCH",
6192
- message: "Routing assertion uses a stale placement epoch",
6576
+ message: "Routing grant uses a stale placement epoch",
6193
6577
  status: 409,
6194
6578
  retryable: true,
6195
6579
  placement,
6196
- internal: true
6580
+ internal: Boolean(assertion)
6197
6581
  });
6198
6582
  }
6199
- return { placement, ...assertion ? { assertion } : {} };
6583
+ if (ticket && ticket.expiresAt <= (input.runtime.routeTickets?.now ?? Date.now)()) {
6584
+ throw routeTicketError("DATAFN_ROUTE_TICKET_EXPIRED");
6585
+ }
6586
+ return { placement, ...assertion ? { assertion } : {}, ...ticket ? { ticket } : {} };
6200
6587
  }
6201
6588
  function createDatafnGatewayRouter(config) {
6202
6589
  const maxBodyBytes = validateDatafnRoutingBodyLimit(config.maxBodyBytes);
@@ -8673,12 +9060,16 @@ function buildReplaceRecord(schema, resourceName, existingRecord, newRecord, res
8673
9060
  result[key] = existingRecord[key];
8674
9061
  continue;
8675
9062
  }
9063
+ if (field.readonly) {
9064
+ result[key] = Object.prototype.hasOwnProperty.call(newRecord, key) ? newRecord[key] : existingRecord[key];
9065
+ continue;
9066
+ }
8676
9067
  if (Object.prototype.hasOwnProperty.call(newRecord, key)) {
8677
9068
  result[key] = newRecord[key];
8678
9069
  } else {
8679
9070
  result[key] = field.default !== void 0 ? field.default : null;
8680
9071
  }
8681
- if (field.required && (result[key] === null || result[key] === void 0)) {
9072
+ if (field.required && (result[key] === void 0 || result[key] === null && !field.nullable)) {
8682
9073
  return {
8683
9074
  ok: false,
8684
9075
  code: "DFQL_INVALID",
@@ -8765,8 +9156,7 @@ function isRecordEffectivelyInactive(record) {
8765
9156
  return isRecordInactive(record) || record?.isAncestorInactive === true;
8766
9157
  }
8767
9158
  function resourceSupportsAncestorInactive(schema, resource) {
8768
- const resourceSchema = schema.resources.find((candidate) => candidate.name === resource);
8769
- return resourceSchema?.fields.some((field) => field.name === "isAncestorInactive") === true;
9159
+ return resourceRequiresAncestorInactive(schema.relations, resource);
8770
9160
  }
8771
9161
  function dependentEndpoint(relation) {
8772
9162
  return relation.type === "many-one" ? relation.from : relation.to;
@@ -10185,7 +10575,7 @@ function decideMergeMode(schema, resource, id, delta) {
10185
10575
  for (const field of resourceDef.fields) {
10186
10576
  if (!field.required) continue;
10187
10577
  if (field.name === "id" || field.name === "__ns") continue;
10188
- const hasProvided = Object.prototype.hasOwnProperty.call(delta, field.name) && delta[field.name] !== void 0 && delta[field.name] !== null;
10578
+ const hasProvided = Object.prototype.hasOwnProperty.call(delta, field.name) && delta[field.name] !== void 0 && (delta[field.name] !== null || field.nullable === true);
10189
10579
  const hasDefault = field.default !== void 0;
10190
10580
  if (!hasProvided && !hasDefault) return { mode: "not_found" };
10191
10581
  }
@@ -11924,6 +12314,64 @@ async function drainPermissionDirectoryOutbox(db, runtime, logger, limit = 100)
11924
12314
  }
11925
12315
  return { processed, pending: tasks.length - processed };
11926
12316
  }
12317
+ async function drainNamespacePermissionDirectoryOutbox(db, namespace, runtime, logger, options = {}) {
12318
+ await ensurePermissionDirectoryOutbox(db);
12319
+ const limit = options.limit ?? 100;
12320
+ const maxRounds = options.maxRounds ?? 32;
12321
+ let processed = 0;
12322
+ for (let round = 0; round < maxRounds; round += 1) {
12323
+ const tasks = await db.internal.findMany(OUTBOX_TABLE, [
12324
+ { field: "namespace", op: "eq", value: namespace },
12325
+ { field: "region_id", op: "eq", value: runtime.regionId },
12326
+ { field: "next_attempt_at", op: "lte", value: (/* @__PURE__ */ new Date()).toISOString() }
12327
+ ], {
12328
+ orderBy: "next_attempt_at",
12329
+ limit
12330
+ });
12331
+ if (tasks.length === 0) {
12332
+ break;
12333
+ }
12334
+ let roundProcessed = 0;
12335
+ for (const task of tasks) {
12336
+ const taskId = String(task.id);
12337
+ const selectedNextAttemptAt = String(task.next_attempt_at);
12338
+ const claimedNextAttemptAt = new Date(
12339
+ Date.now() + DRAIN_CLAIM_LEASE_MS
12340
+ ).toISOString();
12341
+ const claimed = await db.internal.update(OUTBOX_TABLE, [
12342
+ { field: "id", op: "eq", value: taskId },
12343
+ { field: "namespace", op: "eq", value: namespace },
12344
+ { field: "region_id", op: "eq", value: runtime.regionId },
12345
+ { field: "next_attempt_at", op: "eq", value: selectedNextAttemptAt }
12346
+ ], {
12347
+ next_attempt_at: claimedNextAttemptAt
12348
+ });
12349
+ if (claimed === 0) continue;
12350
+ if (await drainPermissionDirectorySync(
12351
+ db,
12352
+ taskId,
12353
+ runtime,
12354
+ logger,
12355
+ { expectedNextAttemptAt: claimedNextAttemptAt }
12356
+ )) {
12357
+ processed += 1;
12358
+ roundProcessed += 1;
12359
+ }
12360
+ }
12361
+ if (roundProcessed === 0) {
12362
+ const remaining2 = await db.internal.findMany(OUTBOX_TABLE, [
12363
+ { field: "namespace", op: "eq", value: namespace },
12364
+ { field: "region_id", op: "eq", value: runtime.regionId }
12365
+ ], { limit: 1 });
12366
+ return { processed, pending: remaining2.length };
12367
+ }
12368
+ }
12369
+ const remaining = await db.internal.findMany(OUTBOX_TABLE, [
12370
+ { field: "namespace", op: "eq", value: namespace },
12371
+ { field: "region_id", op: "eq", value: runtime.regionId }
12372
+ ], { limit: 1 });
12373
+ return { processed, pending: remaining.length };
12374
+ }
11927
12375
 
11928
12376
  // src/execution/mutation/execute.ts
11929
12377
  var FAILED_SHARE_COMPENSATION_RESULT = /* @__PURE__ */ Symbol("failedShareCompensation");
@@ -12025,6 +12473,23 @@ async function executeMutationCore(mutation, db, schema, namespace, effectiveMut
12025
12473
  let additionalChanges = [];
12026
12474
  let skipChangeTracking = false;
12027
12475
  let failedShareCompensation = null;
12476
+ if ((mutation.operation === "insert" || mutation.operation === "merge" || mutation.operation === "replace") && mutation.record) {
12477
+ const systemField = findSystemFieldWrite(schema.relations, mutation.resource, mutation.record);
12478
+ if (systemField) {
12479
+ return {
12480
+ ok: false,
12481
+ mutationId: effectiveMutationId,
12482
+ affectedIds: [],
12483
+ errors: [{
12484
+ code: "DFQL_INVALID",
12485
+ message: `Field is read-only: ${systemField} on ${mutation.resource}`,
12486
+ path: `record.${systemField}`,
12487
+ retryable: false
12488
+ }],
12489
+ deduped: false
12490
+ };
12491
+ }
12492
+ }
12028
12493
  try {
12029
12494
  switch (mutation.operation) {
12030
12495
  case "insert":
@@ -13337,6 +13802,16 @@ async function executeTransaction(request, schema, db, idempotencyStore, limits,
13337
13802
  const steps = request.steps;
13338
13803
  const isAtomic = request.atomic !== false;
13339
13804
  const hasMutations = steps.some((step) => Boolean(step.mutation));
13805
+ if (isAtomic && hasMutations && db.capabilities?.transactions?.supported === false) {
13806
+ return {
13807
+ ok: false,
13808
+ error: {
13809
+ code: "DFQL_UNSUPPORTED",
13810
+ message: "Atomic transact with mutations requires database transactions, which this adapter does not support; send atomic: false to apply steps one at a time",
13811
+ details: { path: "atomic" }
13812
+ }
13813
+ };
13814
+ }
13340
13815
  const multiRegionRuntime = getDatafnMultiRegionRuntimeConfig(plugins);
13341
13816
  const needsPermissionDirectoryOutbox = Boolean(
13342
13817
  hasMutations && multiRegionRuntime && steps.some(
@@ -13459,7 +13934,7 @@ async function executeTransaction(request, schema, db, idempotencyStore, limits,
13459
13934
  }
13460
13935
  return null;
13461
13936
  };
13462
- if (isAtomic && typeof db.transaction === "function") {
13937
+ if (isAtomic && db.capabilities?.transactions?.supported !== false && typeof db.transaction === "function") {
13463
13938
  const deferredPermissionDirectorySyncs = [];
13464
13939
  const reconcilePermissionDirectoryAfterSettlement = async () => {
13465
13940
  await drainPrequeuedUnshareTasks();
@@ -14484,7 +14959,7 @@ function compareCanonicalChangeEntries(a, b) {
14484
14959
  function mergeCanonicalChangeStreamsBounded(streams, limit) {
14485
14960
  const heads = streams.filter((stream) => stream.changes.length > 0).map((stream) => ({ resource: stream.resource, changes: stream.changes, index: 0 }));
14486
14961
  const merged = [];
14487
- const latestCursorPerResource = {};
14962
+ const latestCursorPerResource = /* @__PURE__ */ Object.create(null);
14488
14963
  let peakWindow = heads.length;
14489
14964
  while (heads.length > 0 && merged.length < limit) {
14490
14965
  let bestIdx = 0;
@@ -14716,11 +15191,11 @@ async function executePullCanonical(request, schema, db, namespace, sequenceStor
14716
15191
  const requestedResourceKeys = Object.keys(request.cursors).filter(
14717
15192
  (resource) => resource !== ACTOR_FEED_CURSOR_KEY
14718
15193
  );
14719
- const records = {};
14720
- const merged = {};
14721
- const deleted = {};
14722
- const joins = {};
14723
- const cursors = {};
15194
+ const records = /* @__PURE__ */ Object.create(null);
15195
+ const merged = /* @__PURE__ */ Object.create(null);
15196
+ const deleted = /* @__PURE__ */ Object.create(null);
15197
+ const joins = /* @__PURE__ */ Object.create(null);
15198
+ const cursors = /* @__PURE__ */ Object.create(null);
14724
15199
  for (const resource of requestedResourceKeys) {
14725
15200
  if (!resource.startsWith("join_") && !resource.startsWith("__datafn_")) {
14726
15201
  records[resource] = [];
@@ -15123,6 +15598,17 @@ async function executePush(request, schema, db, idempotencyStore, namespace, seq
15123
15598
  const batchLocalSeen = /* @__PURE__ */ new Map();
15124
15599
  async function executeMutationOp(mut, targetDb) {
15125
15600
  const resolvedCapabilities = resolveCapabilitiesForResource2(schema, mut.resource);
15601
+ if ((mut.operation === "insert" || mut.operation === "merge" || mut.operation === "replace") && typeof mut.record === "object" && mut.record !== null) {
15602
+ const systemField = findSystemFieldWrite(schema.relations, mut.resource, mut.record);
15603
+ if (systemField) {
15604
+ return {
15605
+ ok: false,
15606
+ code: "DFQL_INVALID",
15607
+ message: `Field is read-only: ${systemField} on ${mut.resource}`,
15608
+ path: `record.${systemField}`
15609
+ };
15610
+ }
15611
+ }
15126
15612
  switch (mut.operation) {
15127
15613
  case "insert": {
15128
15614
  const coercedData = applyDateCoercion(schema, mut.resource, mut.record || {}, logger);
@@ -17653,6 +18139,7 @@ var WebSocketManager = class {
17653
18139
  * Reverse mapping: client → known principalIds for O(1) targeted index cleanup.
17654
18140
  */
17655
18141
  this.clientPrincipals = /* @__PURE__ */ new Map();
18142
+ this.routeTickets = /* @__PURE__ */ new Map();
17656
18143
  this.clientPlacement = /* @__PURE__ */ new Map();
17657
18144
  /** Monotonic namespace fence generation closes the validation/registration race. */
17658
18145
  this.namespaceFenceGeneration = /* @__PURE__ */ new Map();
@@ -17804,6 +18291,11 @@ var WebSocketManager = class {
17804
18291
  */
17805
18292
  addClient(client, authContext) {
17806
18293
  const { namespace } = authContext;
18294
+ if (this.clientNamespace.has(client)) return false;
18295
+ if (authContext.routeTicket && authContext.routeTicket.expiresAt <= (authContext.routeTicket.now ?? Date.now)()) {
18296
+ this.closeClientSafely(client, 4511, "DATAFN_ROUTE_TICKET_EXPIRED", "ws-ticket-expired");
18297
+ return false;
18298
+ }
17807
18299
  if (this.closed) {
17808
18300
  this.closeClientSafely(client, 1001, "Going Away", "ws-closed-admission");
17809
18301
  return false;
@@ -17837,6 +18329,12 @@ var WebSocketManager = class {
17837
18329
  ...authContext.regionId ? { regionId: authContext.regionId } : {},
17838
18330
  ...Number.isSafeInteger(authContext.routingEpoch) ? { epoch: authContext.routingEpoch } : {}
17839
18331
  });
18332
+ if (authContext.routeTicket) {
18333
+ const { id, expiresAt, now = Date.now } = authContext.routeTicket;
18334
+ const timer = setTimeout(() => this.expireRouteClient(client), Math.max(0, expiresAt - now()));
18335
+ timer.unref?.();
18336
+ this.routeTickets.set(client, { id, expiresAt, now, timer });
18337
+ }
17840
18338
  if (this.heartbeatTimer === null) {
17841
18339
  this.startHeartbeat();
17842
18340
  }
@@ -17845,7 +18343,24 @@ var WebSocketManager = class {
17845
18343
  /**
17846
18344
  * Handle disconnection.
17847
18345
  */
18346
+ expireRouteClient(client) {
18347
+ this.removeClient(client);
18348
+ this.closeClientSafely(client, 4511, "DATAFN_ROUTE_TICKET_EXPIRED", "ws-ticket-expired");
18349
+ }
18350
+ revokeRouteTicket(ticketId) {
18351
+ let count = 0;
18352
+ for (const [client, ticket] of this.routeTickets) {
18353
+ if (ticket.id !== ticketId) continue;
18354
+ this.removeClient(client);
18355
+ this.closeClientSafely(client, 4403, "DATAFN_ROUTE_TICKET_REVOKED", "ws-ticket-revoked");
18356
+ count++;
18357
+ }
18358
+ return count;
18359
+ }
17848
18360
  removeClient(client) {
18361
+ const ticket = this.routeTickets.get(client);
18362
+ if (ticket) clearTimeout(ticket.timer);
18363
+ this.routeTickets.delete(client);
17849
18364
  const namespace = this.clientNamespace.get(client);
17850
18365
  if (namespace !== void 0) {
17851
18366
  this.removeTargetingIndexes(client, namespace);
@@ -17962,9 +18477,16 @@ var WebSocketManager = class {
17962
18477
  principals: mode === "targeted" ? Array.from(requestedPrincipals).sort() : void 0
17963
18478
  }
17964
18479
  });
18480
+ let sent = 0;
17965
18481
  for (const client of recipients) {
18482
+ const ticket = this.routeTickets.get(client);
18483
+ if (ticket && ticket.expiresAt <= ticket.now()) {
18484
+ this.expireRouteClient(client);
18485
+ continue;
18486
+ }
17966
18487
  try {
17967
18488
  client.send(msg);
18489
+ sent++;
17968
18490
  } catch (e) {
17969
18491
  this.logger?.error("Error sending to websocket client", { error: String(e), operation: "ws-broadcast" });
17970
18492
  this.removeClient(client);
@@ -17974,7 +18496,7 @@ var WebSocketManager = class {
17974
18496
  return {
17975
18497
  mode,
17976
18498
  degraded,
17977
- wokenClients: mode === "namespace-broadcast" ? "all-in-namespace" : recipients.size
18499
+ wokenClients: mode === "namespace-broadcast" ? "all-in-namespace" : sent
17978
18500
  };
17979
18501
  }
17980
18502
  /**
@@ -17993,6 +18515,8 @@ var WebSocketManager = class {
17993
18515
  this.clientNamespace.clear();
17994
18516
  this.clientPrincipals.clear();
17995
18517
  this.clientPlacement.clear();
18518
+ for (const ticket of this.routeTickets.values()) clearTimeout(ticket.timer);
18519
+ this.routeTickets.clear();
17996
18520
  this.pendingPong.clear();
17997
18521
  }
17998
18522
  /**
@@ -18199,35 +18723,6 @@ function relationReferencesInternalResource(relation, internalResourceNames) {
18199
18723
  function normalizeResourceEndpoint(endpoint) {
18200
18724
  return typeof endpoint === "string" ? [endpoint] : [...endpoint];
18201
18725
  }
18202
- function payloadReferencesInternalResource(payload, internalResourceNames) {
18203
- if (internalResourceNames.size === 0) {
18204
- return false;
18205
- }
18206
- if (Array.isArray(payload)) {
18207
- return payload.some((entry) => payloadReferencesInternalResource(entry, internalResourceNames));
18208
- }
18209
- if (!payload || typeof payload !== "object") {
18210
- return false;
18211
- }
18212
- const record = payload;
18213
- if (typeof record.resource === "string" && internalResourceNames.has(record.resource)) {
18214
- return true;
18215
- }
18216
- if (Array.isArray(record.resources) && record.resources.some((resource) => typeof resource === "string" && internalResourceNames.has(resource))) {
18217
- return true;
18218
- }
18219
- for (const key of ["mutations", "queries", "steps", "operations"]) {
18220
- if (Array.isArray(record[key]) && payloadReferencesInternalResource(record[key], internalResourceNames)) {
18221
- return true;
18222
- }
18223
- }
18224
- for (const key of ["query", "mutation", "payload"]) {
18225
- if (record[key] && payloadReferencesInternalResource(record[key], internalResourceNames)) {
18226
- return true;
18227
- }
18228
- }
18229
- return false;
18230
- }
18231
18726
  function normalizePluginAuthorizationError(error, pluginName) {
18232
18727
  if (error && typeof error === "object") {
18233
18728
  const candidate = error;
@@ -18826,10 +19321,10 @@ async function createDatafnServer(config) {
18826
19321
  }
18827
19322
  return { ok: true };
18828
19323
  };
18829
- const withAuth = (action, handler) => {
19324
+ const withAuth = (action, handler, origin = "http", rest = false) => {
18830
19325
  return async (req, ctx) => {
18831
19326
  const enrichedCtx = createEnrichedContext(ctx);
18832
- const placementRequest = multiRegionRuntime?.placement ? req.clone() : void 0;
19327
+ const placementRequest = multiRegionRuntime?.placement && origin === "http" ? req.clone() : void 0;
18833
19328
  let payload = null;
18834
19329
  if (shuttingDown) {
18835
19330
  return completeDatafnResponse({
@@ -18958,7 +19453,36 @@ async function createDatafnServer(config) {
18958
19453
  }
18959
19454
  enrichedCtx.parsedBody = payload;
18960
19455
  }
18961
- if (payloadReferencesInternalResource(payload, internalResourceNames)) {
19456
+ let structuralPayload = payload;
19457
+ if (rest) {
19458
+ let resource;
19459
+ try {
19460
+ const segment = sanitizePathSegment(new URL(req.url).pathname.split("/")[3] ?? "");
19461
+ if (!segment.ok) throw new Error("Invalid path segment");
19462
+ resource = segment.value;
19463
+ } catch {
19464
+ return completeDatafnResponse({
19465
+ action,
19466
+ request: req,
19467
+ context: enrichedCtx,
19468
+ payload,
19469
+ response: errorResponse({ code: "DFQL_INVALID", message: "Invalid path segment", details: { path: "resource" } }, 400)
19470
+ });
19471
+ }
19472
+ structuralPayload = { resource };
19473
+ }
19474
+ const parsedProtocol = parseDatafnRequest(action, structuralPayload, { schema: validatedSchema });
19475
+ if (!parsedProtocol.ok) {
19476
+ return completeDatafnResponse({
19477
+ action,
19478
+ request: req,
19479
+ context: enrichedCtx,
19480
+ payload,
19481
+ response: errorResponse(parsedProtocol.error, 400)
19482
+ });
19483
+ }
19484
+ const selection = collectStructuralResourceSelectors(parsedProtocol.result);
19485
+ if (selection.selectors.some((resource) => internalResourceNames.has(resource))) {
18962
19486
  await emitDataFnEvent({
18963
19487
  domain: "datafn",
18964
19488
  type: "datafn.authorization.denied",
@@ -18984,7 +19508,9 @@ async function createDatafnServer(config) {
18984
19508
  namespace: await extractNamespace(enrichedCtx),
18985
19509
  regionId: multiRegionRuntime.regionId,
18986
19510
  runtime: multiRegionRuntime.placement,
18987
- request: placementRequest
19511
+ request: placementRequest,
19512
+ scope: action,
19513
+ trustedInternal: origin === "executor"
18988
19514
  });
18989
19515
  } catch (error) {
18990
19516
  if (error instanceof DatafnRoutingError) {
@@ -19003,7 +19529,7 @@ async function createDatafnServer(config) {
19003
19529
  action,
19004
19530
  request: req,
19005
19531
  context: enrichedCtx,
19006
- payload
19532
+ payload: structuralPayload
19007
19533
  });
19008
19534
  if (!pluginAuthorization.ok) {
19009
19535
  await emitDataFnEvent({
@@ -19023,7 +19549,7 @@ async function createDatafnServer(config) {
19023
19549
  });
19024
19550
  }
19025
19551
  if (config.authorize) {
19026
- const authorized = await config.authorize(enrichedCtx, action, payload);
19552
+ const authorized = await config.authorize(enrichedCtx, action, structuralPayload);
19027
19553
  if (!authorized) {
19028
19554
  await emitDataFnEvent({
19029
19555
  domain: "datafn",
@@ -19098,7 +19624,7 @@ async function createDatafnServer(config) {
19098
19624
  try {
19099
19625
  const configuredContext = config.context;
19100
19626
  const executorContext = context ?? (typeof configuredContext === "function" ? await configuredContext(request) : configuredContext ?? {});
19101
- response = await withAuth(action, handler)(request, executorContext);
19627
+ response = await withAuth(action, handler, "executor")(request, executorContext);
19102
19628
  } catch {
19103
19629
  throw new DatafnExecutorError(
19104
19630
  { code: "INTERNAL", message: "Internal Server Error" },
@@ -19288,7 +19814,9 @@ async function createDatafnServer(config) {
19288
19814
  method: route.method,
19289
19815
  path: route.path,
19290
19816
  meta: route.meta,
19291
- handler: withAuth(action, route.handler)
19817
+ // withAuth and the REST handler validate URL segments and complete DataFn response hooks.
19818
+ decodeParams: false,
19819
+ handler: withAuth(action, route.handler, "http", true)
19292
19820
  });
19293
19821
  }
19294
19822
  }
@@ -19460,12 +19988,18 @@ async function createDatafnServer(config) {
19460
19988
  regionId: multiRegionRuntime.regionId,
19461
19989
  runtime: multiRegionRuntime.placement,
19462
19990
  request: handshakeRequest,
19463
- trustedInternal: !handshakeRequest && !multiRegionRuntime.placement.requireRoutingAssertion
19991
+ scope: "websocket",
19992
+ trustedInternal: !handshakeRequest && !multiRegionRuntime.placement.requireRoutingAssertion && !multiRegionRuntime.placement.routeTickets
19464
19993
  });
19465
19994
  added = wsManager.addClient(client, {
19466
19995
  ...authContext,
19467
19996
  regionId: validated.placement.regionId,
19468
- routingEpoch: validated.placement.epoch
19997
+ routingEpoch: validated.placement.epoch,
19998
+ routeTicket: validated.ticket ? {
19999
+ id: validated.ticket.ticketId,
20000
+ expiresAt: validated.ticket.expiresAt,
20001
+ now: multiRegionRuntime.placement.routeTickets?.now
20002
+ } : void 0
19469
20003
  });
19470
20004
  if (!added) return false;
19471
20005
  if (wsManager.getNamespaceFenceGeneration(authContext.namespace) !== fenceGeneration) {
@@ -19484,7 +20018,7 @@ async function createDatafnServer(config) {
19484
20018
  if (added) wsManager.removeClient(client);
19485
20019
  try {
19486
20020
  client.close(
19487
- error instanceof DatafnRoutingError ? 4510 : 1011,
20021
+ error instanceof DatafnRoutingError ? error.code === "DATAFN_ROUTE_RATE_LIMITED" ? 4503 : error.code === "DATAFN_ROUTE_TICKET_EXPIRED" ? 4511 : error.code.startsWith("DATAFN_ROUTE_") ? 4403 : 4510 : 1011,
19488
20022
  error instanceof Error ? error.message : "Placement validation failed"
19489
20023
  );
19490
20024
  } catch {
@@ -19492,6 +20026,7 @@ async function createDatafnServer(config) {
19492
20026
  return false;
19493
20027
  }
19494
20028
  },
20029
+ revokeRouteTicket: (ticketId) => wsManager.revokeRouteTicket(ticketId),
19495
20030
  fenceNamespace: (namespace, minimumEpoch) => wsManager.fenceNamespace(namespace, minimumEpoch),
19496
20031
  removeClient: (client) => wsManager.removeClient(client),
19497
20032
  handleMessage: (client, data) => wsManager.handleMessage(client, data),
@@ -20429,6 +20964,685 @@ function bytesToBase64Url(bytes) {
20429
20964
  return Buffer.from(bytes).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
20430
20965
  }
20431
20966
 
20432
- export { AtomicSequenceStore, ChainedSequenceStore, DATAFN_MULTI_REGION_CAPABILITY, DATAFN_ROUTING_ASSERTION_HEADER, DATAFN_ROUTING_INTERNAL_HEADERS, DatabaseSequenceStore, DatafnExecutorError, DatafnPublicLinkInputError, DatafnRoutingError, claimDatafnNamespacePlacement, createConditionalKvDatafnPlacementDirectory, createDatafnGatewayRouter, createDatafnHmacRoutingAssertions, createDatafnMultiRegionPlugin, createDatafnPublicLinksPlugin, createDatafnServer, createMemoryDatafnPlacementDirectory, createMemoryDatafnRoutingReplayStore, createSequenceStore, datafn, datafnMultiRegionPlugin, migrateDatafnNamespace, readDatafnPublicLinkToken, resolveDatafnPublicLink, validateDatafnPlacement, validateDatafnRoutingBodyLimit, withDatafnPublicLinksSchema, withDatafnRoutingAssertion };
20967
+ // src/placement-policy.ts
20968
+ var CONTINENT_CENTERS = {
20969
+ AF: [1.65, 17.68],
20970
+ AN: [-82.86, 135],
20971
+ AS: [34.05, 100.62],
20972
+ EU: [54.53, 15.26],
20973
+ NA: [54.53, -105.26],
20974
+ OC: [-22.74, 140.02],
20975
+ SA: [-14.24, -51.93]
20976
+ };
20977
+ function finiteCoordinate(value, minimum, maximum) {
20978
+ return value !== void 0 && Number.isFinite(value) && value >= minimum && value <= maximum;
20979
+ }
20980
+ function normalizedCandidates(input) {
20981
+ const context = {
20982
+ location: input.location ?? null,
20983
+ preferredRegionId: normalizedPreferredRegionId(input.preferredRegionId)
20984
+ };
20985
+ const seen = /* @__PURE__ */ new Set();
20986
+ const candidates = input.candidates.map((candidate) => {
20987
+ const regionId = candidate.regionId.trim();
20988
+ if (!regionId) throw new Error("DATAFN_PLACEMENT_REGION_ID_REQUIRED");
20989
+ if (seen.has(regionId)) {
20990
+ throw new Error(`DATAFN_PLACEMENT_REGION_DUPLICATE: ${regionId}`);
20991
+ }
20992
+ seen.add(regionId);
20993
+ return regionId === candidate.regionId ? candidate : { ...candidate, regionId };
20994
+ });
20995
+ return candidates.filter(
20996
+ (candidate) => (input.constraints ?? []).every(
20997
+ (constraint) => constraint(candidate, context)
20998
+ )
20999
+ );
21000
+ }
21001
+ function normalizedPreferredRegionId(preferredRegionId) {
21002
+ return preferredRegionId?.trim() || null;
21003
+ }
21004
+ function compareRegionIds(left, right) {
21005
+ return left < right ? -1 : left > right ? 1 : 0;
21006
+ }
21007
+ function sourceCoordinates(location) {
21008
+ if (!location) return null;
21009
+ if (finiteCoordinate(location.latitude, -90, 90) && finiteCoordinate(location.longitude, -180, 180)) {
21010
+ return {
21011
+ coordinates: [location.latitude, location.longitude],
21012
+ source: "coordinates"
21013
+ };
21014
+ }
21015
+ const continent = location.continent?.toUpperCase();
21016
+ const coordinates = continent ? CONTINENT_CENTERS[continent] : void 0;
21017
+ return coordinates ? { coordinates, source: "continent" } : null;
21018
+ }
21019
+ function radians(degrees) {
21020
+ return degrees * Math.PI / 180;
21021
+ }
21022
+ function distanceKilometers(source, target) {
21023
+ const sourceLatitude = radians(source[0]);
21024
+ const targetLatitude = radians(target[0]);
21025
+ const latitudeDelta = radians(target[0] - source[0]);
21026
+ const longitudeDelta = radians(target[1] - source[1]);
21027
+ const haversine = Math.sin(latitudeDelta / 2) ** 2 + Math.cos(sourceLatitude) * Math.cos(targetLatitude) * Math.sin(longitudeDelta / 2) ** 2;
21028
+ const clampedHaversine = Math.min(1, Math.max(0, haversine));
21029
+ return 6371 * 2 * Math.atan2(Math.sqrt(clampedHaversine), Math.sqrt(1 - clampedHaversine));
21030
+ }
21031
+ function rankDatafnPlacementRegions(input) {
21032
+ const candidates = normalizedCandidates(input);
21033
+ const source = sourceCoordinates(input.location ?? null);
21034
+ if (!source) return [];
21035
+ return candidates.flatMap((candidate) => {
21036
+ const { latitude, longitude } = candidate;
21037
+ return finiteCoordinate(latitude, -90, 90) && finiteCoordinate(longitude, -180, 180) ? [
21038
+ {
21039
+ regionId: candidate.regionId,
21040
+ source: source.source,
21041
+ distanceKilometers: distanceKilometers(source.coordinates, [
21042
+ latitude,
21043
+ longitude
21044
+ ])
21045
+ }
21046
+ ] : [];
21047
+ }).sort(
21048
+ (left, right) => (left.distanceKilometers ?? 0) - (right.distanceKilometers ?? 0) || compareRegionIds(left.regionId, right.regionId)
21049
+ );
21050
+ }
21051
+ function stableIndex(key, length) {
21052
+ let hash = 2166136261;
21053
+ for (const byte of new TextEncoder().encode(key)) {
21054
+ hash ^= byte;
21055
+ hash = Math.imul(hash, 16777619) >>> 0;
21056
+ }
21057
+ return hash % length;
21058
+ }
21059
+ function selectDatafnPlacementRegion(input) {
21060
+ const candidates = normalizedCandidates(input);
21061
+ const preferredRegionId = normalizedPreferredRegionId(
21062
+ input.preferredRegionId
21063
+ );
21064
+ if (preferredRegionId && candidates.some((candidate) => candidate.regionId === preferredRegionId)) {
21065
+ return { regionId: preferredRegionId, source: "preferred" };
21066
+ }
21067
+ const ranked = rankDatafnPlacementRegions({
21068
+ candidates,
21069
+ location: input.location ?? null
21070
+ });
21071
+ const nearest = ranked[0];
21072
+ if (nearest) return nearest;
21073
+ if (input.stableKey !== void 0 && candidates.length > 0) {
21074
+ const stableCandidates = [...candidates].sort(
21075
+ (left, right) => compareRegionIds(left.regionId, right.regionId)
21076
+ );
21077
+ const selected = stableCandidates[stableIndex(input.stableKey, stableCandidates.length)];
21078
+ if (selected) {
21079
+ return { regionId: selected.regionId, source: "stable-fallback" };
21080
+ }
21081
+ }
21082
+ return null;
21083
+ }
21084
+ function coordinate(value, minimum, maximum) {
21085
+ const parsed = typeof value === "number" ? value : Number(value);
21086
+ return Number.isFinite(parsed) && parsed >= minimum && parsed <= maximum ? parsed : void 0;
21087
+ }
21088
+ function readDatafnCloudflarePlacementLocation(request) {
21089
+ const cf = request.cf;
21090
+ if (!cf) return null;
21091
+ const latitude = coordinate(cf.latitude, -90, 90);
21092
+ const longitude = coordinate(cf.longitude, -180, 180);
21093
+ const continent = typeof cf.continent === "string" && /^[A-Za-z]{2}$/u.test(cf.continent) ? cf.continent.toUpperCase() : void 0;
21094
+ if (latitude === void 0 && longitude === void 0 && !continent)
21095
+ return null;
21096
+ return {
21097
+ ...latitude === void 0 ? {} : { latitude },
21098
+ ...longitude === void 0 ? {} : { longitude },
21099
+ ...continent ? { continent } : {}
21100
+ };
21101
+ }
21102
+ var POSTGRES_IDENTIFIER_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
21103
+ var DATAFN_INTERNAL_TABLE_RE = /^__datafn_[a-z0-9_]+$/;
21104
+ var LEGACY_PERMISSIONS_TABLE_RE = /^__datafn_permissions_(?!global$)[A-Za-z0-9_]+$/;
21105
+ var POSTGRES_NAMESPACE_STORAGE_CATALOG_SQL = `
21106
+ SELECT c.table_name, c.column_name
21107
+ FROM information_schema.columns AS c
21108
+ JOIN information_schema.tables AS t
21109
+ ON t.table_schema = c.table_schema
21110
+ AND t.table_name = c.table_name
21111
+ WHERE c.table_schema = current_schema()
21112
+ AND t.table_type = 'BASE TABLE'
21113
+ ORDER BY c.table_name, c.ordinal_position
21114
+ `.trim();
21115
+ var INTERNAL_ROLE_BY_TABLE = {
21116
+ __datafn_meta: "sync_meta",
21117
+ __datafn_changes: "sync_changes",
21118
+ __datafn_idempotency: "idempotency",
21119
+ __datafn_seed: "seed",
21120
+ __datafn_permission_directory_outbox: "permission_directory_outbox"
21121
+ };
21122
+ var SHARING_RESOURCE_TABLES = [
21123
+ {
21124
+ logicalRole: "permissions_global",
21125
+ relation: "__datafn_permissions_global"
21126
+ },
21127
+ {
21128
+ logicalRole: "principal_memberships",
21129
+ relation: "__datafn_principal_memberships"
21130
+ },
21131
+ {
21132
+ logicalRole: "principal_hierarchy",
21133
+ relation: "__datafn_principal_hierarchy"
21134
+ }
21135
+ ];
21136
+ var SELECTOR_COLUMN = {
21137
+ resource_ns: "__ns",
21138
+ internal_namespace: "namespace"
21139
+ };
21140
+ var DatafnNamespaceStorageError = class extends Error {
21141
+ constructor(input) {
21142
+ super(input.message);
21143
+ this.name = "DatafnNamespaceStorageError";
21144
+ this.code = input.code;
21145
+ this.details = input.details;
21146
+ }
21147
+ };
21148
+ function fail(code, message, details) {
21149
+ throw new DatafnNamespaceStorageError({ code, message, details });
21150
+ }
21151
+ function quotePostgresIdentifier(identifier) {
21152
+ if (!POSTGRES_IDENTIFIER_RE.test(identifier)) {
21153
+ fail(
21154
+ "DATAFN_NAMESPACE_STORAGE_INVALID",
21155
+ `Invalid PostgreSQL identifier "${identifier}"`,
21156
+ { identifier }
21157
+ );
21158
+ }
21159
+ return `"${identifier}"`;
21160
+ }
21161
+ function namespacedInternalTableRoles() {
21162
+ return INTERNAL_ROLE_BY_TABLE;
21163
+ }
21164
+ function catalogByName(catalog) {
21165
+ const map = /* @__PURE__ */ new Map();
21166
+ for (const relation of catalog.relations) {
21167
+ if (map.has(relation.name)) fail("DATAFN_NAMESPACE_STORAGE_INVALID", "Duplicate catalog relation.");
21168
+ map.set(relation.name, relation);
21169
+ }
21170
+ return map;
21171
+ }
21172
+ function hasColumn(relation, column) {
21173
+ return Boolean(relation?.columns.includes(column));
21174
+ }
21175
+ function isShareableResource(schema, resourceName) {
21176
+ const resource = schema.resources.find((entry) => entry.name === resourceName);
21177
+ if (!resource) return false;
21178
+ const resolved = resolveCapabilities(schema.capabilities, resource.capabilities);
21179
+ return resolved.some(
21180
+ (entry) => typeof entry === "object" && entry !== null && "shareable" in entry
21181
+ );
21182
+ }
21183
+ function schemaDerivedRelations(schema) {
21184
+ const planned = [];
21185
+ const resourceRole = namespaceStorageManifestEntry("resource");
21186
+ schema.resources.forEach((resource, index) => {
21187
+ planned.push({
21188
+ logicalRole: "resource",
21189
+ relation: resource.name,
21190
+ requiredColumns: [
21191
+ "id",
21192
+ ...resource.fields.map((field) => field.name),
21193
+ ...getCapabilityFields(resolveCapabilities(schema.capabilities, resource.capabilities)).map((field) => field.name)
21194
+ ].map(physicalColumn),
21195
+ copyOrder: resourceRole.copyOrder + index
21196
+ });
21197
+ });
21198
+ const joinRole = namespaceStorageManifestEntry("join");
21199
+ const joinTables = /* @__PURE__ */ new Set();
21200
+ for (const relation of schema.relations ?? []) {
21201
+ if (relation.type !== "many-many") continue;
21202
+ const table = getRelationJoinTableName(relation);
21203
+ if (joinTables.has(table)) continue;
21204
+ joinTables.add(table);
21205
+ planned.push({
21206
+ logicalRole: "join",
21207
+ relation: table,
21208
+ requiredColumns: [
21209
+ "id",
21210
+ relation.joinColumns?.from ?? "from",
21211
+ relation.joinColumns?.to ?? "to",
21212
+ ...(relation.metadata ?? []).map((field) => field.name)
21213
+ ].map(physicalColumn),
21214
+ copyOrder: joinRole.copyOrder + joinTables.size
21215
+ });
21216
+ }
21217
+ const legacyRole = namespaceStorageManifestEntry("permissions_legacy");
21218
+ schema.resources.forEach((resource, index) => {
21219
+ if (!isShareableResource(schema, resource.name)) return;
21220
+ planned.push({
21221
+ logicalRole: "permissions_legacy",
21222
+ relation: getLegacyPermissionsTable(resource.name),
21223
+ copyOrder: legacyRole.copyOrder + index
21224
+ });
21225
+ });
21226
+ return planned;
21227
+ }
21228
+ function internalPlannedRelations() {
21229
+ return Object.entries(INTERNAL_ROLE_BY_TABLE).map(([relation, logicalRole]) => ({
21230
+ logicalRole,
21231
+ relation,
21232
+ copyOrder: namespaceStorageManifestEntry(logicalRole).copyOrder
21233
+ }));
21234
+ }
21235
+ function sharingPlannedRelations() {
21236
+ return SHARING_RESOURCE_TABLES.map((entry) => ({
21237
+ logicalRole: entry.logicalRole,
21238
+ relation: entry.relation,
21239
+ copyOrder: namespaceStorageManifestEntry(entry.logicalRole).copyOrder
21240
+ }));
21241
+ }
21242
+ function physicalColumn(name) {
21243
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
21244
+ }
21245
+ var SHARING_REQUIRED_COLUMNS = {
21246
+ permissions_global: ["id", "resource_type", "resource_ns", "resource_id", "principal_id", "level", "grant_kind", "source_ref", "granted_by", "granted_at", "revoked_at"],
21247
+ permissions_legacy: ["id", "resource_id", "user_id", "level", "granted_by", "granted_at", "revoked_at"],
21248
+ principal_memberships: ["id", "namespace", "actor_id", "principal_id", "granted_at", "revoked_at"],
21249
+ principal_hierarchy: ["id", "namespace", "principal_id", "parent_principal_id", "created_at", "revoked_at"]
21250
+ };
21251
+ function toEntry(planned, catalog) {
21252
+ const manifest = namespaceStorageManifestEntry(planned.logicalRole);
21253
+ const namespaceColumn = SELECTOR_COLUMN[manifest.selectorKind];
21254
+ const relation = catalog.get(planned.relation);
21255
+ if (!relation) {
21256
+ if (manifest.presence === "schema-derived") {
21257
+ fail(
21258
+ "DATAFN_NAMESPACE_STORAGE_INCOMPLETE",
21259
+ `Required namespace storage relation "${planned.relation}" is missing from the installed schema.`,
21260
+ { logicalRole: planned.logicalRole, relation: planned.relation }
21261
+ );
21262
+ }
21263
+ return null;
21264
+ }
21265
+ if (!hasColumn(relation, namespaceColumn)) {
21266
+ fail(
21267
+ "DATAFN_NAMESPACE_STORAGE_INCOMPLETE",
21268
+ `Namespace storage relation "${planned.relation}" is missing selector column "${namespaceColumn}".`,
21269
+ {
21270
+ logicalRole: planned.logicalRole,
21271
+ relation: planned.relation,
21272
+ expectedColumn: namespaceColumn,
21273
+ columns: relation.columns
21274
+ }
21275
+ );
21276
+ }
21277
+ const required = planned.requiredColumns ?? INTERNAL_TABLE_SCHEMAS[planned.relation]?.map((column) => column.name) ?? SHARING_REQUIRED_COLUMNS[planned.logicalRole] ?? ["id"];
21278
+ const missing = required.filter((column) => !hasColumn(relation, column));
21279
+ if (missing.length > 0) {
21280
+ fail("DATAFN_NAMESPACE_STORAGE_INCOMPLETE", `Relation "${planned.relation}" is missing required columns: ${missing.join(", ")}.`);
21281
+ }
21282
+ const hasIdentity = relation.indexes?.some((index) => index.unique && index.primary === true && index.columns.includes("id") && index.columns.every((column) => column === "id" || column === namespaceColumn));
21283
+ if (!hasIdentity) {
21284
+ fail("DATAFN_NAMESPACE_STORAGE_INCOMPLETE", `Relation "${planned.relation}" is missing a validated unique identity index.`);
21285
+ }
21286
+ return {
21287
+ logicalRole: planned.logicalRole,
21288
+ ownership: "datafn",
21289
+ relation: planned.relation,
21290
+ quotedRelation: quotePostgresIdentifier(planned.relation),
21291
+ namespaceColumn,
21292
+ quotedNamespaceColumn: quotePostgresIdentifier(namespaceColumn),
21293
+ operations: manifest.operations,
21294
+ copyOrder: planned.copyOrder,
21295
+ present: true
21296
+ };
21297
+ }
21298
+ function isDatafnOwnedCatalogRelation(name, columns) {
21299
+ if (columns.includes("__ns")) return true;
21300
+ return DATAFN_INTERNAL_TABLE_RE.test(name) && columns.includes("namespace");
21301
+ }
21302
+ function unexpectedCatalogRelations(catalog, plannedNames) {
21303
+ const unexpected = [];
21304
+ for (const relation of catalog.relations) {
21305
+ if (plannedNames.has(relation.name)) continue;
21306
+ if (!isDatafnOwnedCatalogRelation(relation.name, relation.columns)) continue;
21307
+ unexpected.push(relation.name);
21308
+ }
21309
+ return unexpected.sort();
21310
+ }
21311
+ function resolveNamespaceStoragePlan(input) {
21312
+ try {
21313
+ assertSupportedNamespaceStorageVersions({
21314
+ manifestVersion: input.manifestVersion,
21315
+ schemaVersion: input.schemaVersion
21316
+ });
21317
+ } catch (error) {
21318
+ const code = error && typeof error === "object" && "code" in error ? String(error.code) : "DATAFN_NAMESPACE_STORAGE_VERSION_MISMATCH";
21319
+ fail(
21320
+ code,
21321
+ error instanceof Error ? error.message : String(error)
21322
+ );
21323
+ }
21324
+ if (input.catalog.dialect !== "postgres") {
21325
+ fail(
21326
+ "DATAFN_NAMESPACE_STORAGE_UNSUPPORTED",
21327
+ `Namespace storage plans are supported for PostgreSQL only. Received dialect "${String(input.catalog.dialect)}".`
21328
+ );
21329
+ }
21330
+ if (!isNamespaced(input.schema)) {
21331
+ fail(
21332
+ "DATAFN_NAMESPACE_STORAGE_UNSUPPORTED",
21333
+ "Namespace storage plans require a namespaced DataFn schema."
21334
+ );
21335
+ }
21336
+ const catalog = catalogByName(input.catalog);
21337
+ const planned = [
21338
+ ...schemaDerivedRelations(input.schema),
21339
+ ...sharingPlannedRelations(),
21340
+ ...internalPlannedRelations()
21341
+ ];
21342
+ for (const relation of input.catalog.relations) {
21343
+ if (LEGACY_PERMISSIONS_TABLE_RE.test(relation.name) && !planned.some((entry) => entry.relation === relation.name)) {
21344
+ planned.push({
21345
+ logicalRole: "permissions_legacy",
21346
+ relation: relation.name,
21347
+ copyOrder: namespaceStorageManifestEntry("permissions_legacy").copyOrder + 50
21348
+ });
21349
+ }
21350
+ }
21351
+ const plannedNames = new Set(planned.map((entry) => entry.relation));
21352
+ const unexpected = unexpectedCatalogRelations(input.catalog, plannedNames);
21353
+ if (unexpected.length > 0) {
21354
+ fail(
21355
+ "DATAFN_NAMESPACE_STORAGE_UNKNOWN",
21356
+ `Installed schema contains DataFn namespace storage that is not in the supported contract: ${unexpected.join(", ")}.`,
21357
+ { relations: unexpected }
21358
+ );
21359
+ }
21360
+ const entries = planned.map((entry) => toEntry(entry, catalog)).filter((entry) => entry !== null).sort((left, right) => {
21361
+ if (left.copyOrder !== right.copyOrder) return left.copyOrder - right.copyOrder;
21362
+ return left.relation.localeCompare(right.relation);
21363
+ });
21364
+ return {
21365
+ manifestVersion: DATAFN_NAMESPACE_STORAGE_MANIFEST_VERSION,
21366
+ schemaVersion: DATAFN_NAMESPACE_STORAGE_SCHEMA_VERSION,
21367
+ dialect: "postgres",
21368
+ entries
21369
+ };
21370
+ }
21371
+ function selectNamespaceStorageEntries(plan, operation) {
21372
+ const selected = plan.entries.filter((entry) => entry.operations.includes(operation));
21373
+ if (operation === "cleanup") {
21374
+ return [...selected].sort((left, right) => {
21375
+ if (left.copyOrder !== right.copyOrder) return right.copyOrder - left.copyOrder;
21376
+ return right.relation.localeCompare(left.relation);
21377
+ });
21378
+ }
21379
+ return selected;
21380
+ }
21381
+ function composeNamespaceStoragePlan(plan, applicationEntries) {
21382
+ const existing = new Set(plan.entries.map((entry) => entry.relation));
21383
+ const composed = [...plan.entries];
21384
+ for (const entry of applicationEntries) {
21385
+ if (existing.has(entry.relation)) {
21386
+ fail(
21387
+ "DATAFN_NAMESPACE_STORAGE_INVALID",
21388
+ `Application storage relation "${entry.relation}" collides with DataFn-owned storage.`,
21389
+ { relation: entry.relation }
21390
+ );
21391
+ }
21392
+ existing.add(entry.relation);
21393
+ composed.push({
21394
+ logicalRole: "application",
21395
+ ownership: "application",
21396
+ relation: entry.relation,
21397
+ quotedRelation: quotePostgresIdentifier(entry.relation),
21398
+ namespaceColumn: entry.namespaceColumn,
21399
+ quotedNamespaceColumn: quotePostgresIdentifier(entry.namespaceColumn),
21400
+ operations: entry.operations ?? ["copy", "verify", "cleanup", "fence", "backup"],
21401
+ copyOrder: entry.copyOrder ?? 10,
21402
+ present: true
21403
+ });
21404
+ }
21405
+ composed.sort((left, right) => {
21406
+ if (left.copyOrder !== right.copyOrder) return left.copyOrder - right.copyOrder;
21407
+ return left.relation.localeCompare(right.relation);
21408
+ });
21409
+ return { ...plan, entries: composed };
21410
+ }
21411
+ var POSTGRES_NAMESPACE_STORAGE_INDEX_SQL = `
21412
+ SELECT t.relname AS table_name,
21413
+ array_agg(a.attname ORDER BY k.ordinality) AS index_columns,
21414
+ i.indisunique AS index_unique, i.indisprimary AS index_primary
21415
+ FROM pg_index i
21416
+ JOIN pg_class t ON t.oid = i.indrelid
21417
+ JOIN pg_namespace n ON n.oid = t.relnamespace
21418
+ CROSS JOIN LATERAL unnest(i.indkey) WITH ORDINALITY AS k(attnum, ordinality)
21419
+ LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum
21420
+ WHERE n.nspname = current_schema() AND i.indisvalid AND i.indisready
21421
+ AND i.indpred IS NULL AND i.indexprs IS NULL
21422
+ AND k.ordinality <= i.indnkeyatts
21423
+ GROUP BY t.relname, i.indexrelid, i.indisunique, i.indisprimary
21424
+ ORDER BY t.relname, i.indexrelid
21425
+ `.trim();
21426
+ async function inspectPostgresNamespaceStorage(query) {
21427
+ const rows = await query(POSTGRES_NAMESPACE_STORAGE_CATALOG_SQL);
21428
+ const indexRows = await query(POSTGRES_NAMESPACE_STORAGE_INDEX_SQL);
21429
+ const relations = /* @__PURE__ */ new Map();
21430
+ for (const row of rows) {
21431
+ if (typeof row.column_name !== "string") fail("DATAFN_NAMESPACE_STORAGE_INCOMPLETE", "Catalog column metadata is missing.");
21432
+ const columns = relations.get(row.table_name) ?? [];
21433
+ columns.push(row.column_name);
21434
+ relations.set(row.table_name, columns);
21435
+ }
21436
+ return {
21437
+ dialect: "postgres",
21438
+ relations: [...relations.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([name, columns]) => ({ name, columns, indexes: indexRows.filter((row) => row.table_name === name && Array.isArray(row.index_columns) && typeof row.index_unique === "boolean").map((row) => ({ columns: row.index_columns, unique: row.index_unique, primary: row.index_primary === true })) }))
21439
+ };
21440
+ }
21441
+ function assertInternalNamespaceStorageMetadataComplete() {
21442
+ const namespaced = listNamespacedInternalTables();
21443
+ const mapped = Object.keys(INTERNAL_ROLE_BY_TABLE).sort();
21444
+ if (namespaced.join("\0") !== mapped.join("\0")) {
21445
+ fail(
21446
+ "DATAFN_NAMESPACE_STORAGE_INCOMPLETE",
21447
+ "Internal namespace tables are missing from the storage contract.",
21448
+ {
21449
+ namespacedInternalTables: namespaced,
21450
+ mappedInternalTables: mapped,
21451
+ schemas: Object.keys(INTERNAL_TABLE_SCHEMAS).sort()
21452
+ }
21453
+ );
21454
+ }
21455
+ }
21456
+ async function drainNamespaceStorage(input) {
21457
+ const drainEntries = selectNamespaceStorageEntries(input.plan, "drain");
21458
+ if (drainEntries.length === 0) {
21459
+ return { processed: 0, pending: 0 };
21460
+ }
21461
+ const unsupported = drainEntries.filter(
21462
+ (entry) => entry.logicalRole !== "permission_directory_outbox"
21463
+ );
21464
+ if (unsupported.length > 0) {
21465
+ fail(
21466
+ "DATAFN_NAMESPACE_STORAGE_UNSUPPORTED",
21467
+ `No drain implementation for logical roles: ${unsupported.map((entry) => entry.logicalRole).join(", ")}.`,
21468
+ { roles: unsupported.map((entry) => entry.logicalRole) }
21469
+ );
21470
+ }
21471
+ return drainNamespacePermissionDirectoryOutbox(
21472
+ input.adapter,
21473
+ input.namespace,
21474
+ input.runtime,
21475
+ input.logger
21476
+ );
21477
+ }
21478
+ async function resolveAuthoritativeAncestorInactive(adapter, schema, resource, record, namespace, maxGraphNodes) {
21479
+ const active = /* @__PURE__ */ new Set();
21480
+ const resolved = /* @__PURE__ */ new Map();
21481
+ let visited = 0;
21482
+ async function visit(model, row, root = false) {
21483
+ if (typeof row.id !== "string" || row.id.length === 0) {
21484
+ throw new Error("Ancestor repair: malformed record identifier");
21485
+ }
21486
+ const key = JSON.stringify([model, row.id]);
21487
+ if (active.has(key)) throw new Error("Ancestor repair: cycle detected");
21488
+ if (resolved.has(key)) return resolved.get(key);
21489
+ if (++visited > maxGraphNodes) throw new Error("Ancestor repair: maxGraphNodes exceeded");
21490
+ active.add(key);
21491
+ let inherited = false;
21492
+ for (const relation of schema.relations ?? []) {
21493
+ if (relation.inheritsInactive !== true || relation.type === "many-many") continue;
21494
+ const dependent = relation.type === "many-one" ? relation.from : relation.to;
21495
+ if (!endpointIncludes(dependent, model)) continue;
21496
+ const endpoint = relation.type === "many-one" ? relation.to : relation.from;
21497
+ const field = relation.type === "many-one" ? relationFkFieldForManyOne(relation) : relation.type === "htree" ? relation.fkField || relation.foreignKey || relation.inverse || "parentId" : relationFkFieldForOneMany(relation);
21498
+ const parentId = row[field];
21499
+ if (parentId === null || parentId === void 0 || parentId === "") continue;
21500
+ if (typeof parentId !== "string") throw new Error("Ancestor repair: malformed parent link");
21501
+ const resourceField = relation.fkResourceField || (relation.type === "htree" ? `${field.replace(/Id$/, "")}Resource` : `${(relation.type === "many-one" ? relation.relation || "target" : relation.inverse || relation.relation || "source").replace(/Id$/, "")}Resource`);
21502
+ const discriminator = row[resourceField];
21503
+ const inferred = resolveEndpointResource(endpoint, parentId, schema);
21504
+ let parentResource = inferred;
21505
+ if (endpointList(endpoint).length > 1 && discriminator != null) {
21506
+ if (typeof discriminator !== "string" || !endpointIncludes(endpoint, discriminator) || inferred && inferred !== discriminator) {
21507
+ throw new Error("Ancestor repair: invalid parent resource discriminator");
21508
+ }
21509
+ parentResource = discriminator;
21510
+ }
21511
+ if (!parentResource) throw new Error("Ancestor repair: ambiguous parent resource");
21512
+ const parent = await adapter.findOne({
21513
+ model: parentResource,
21514
+ where: [{ field: "id", operator: "eq", value: parentId }],
21515
+ namespace
21516
+ });
21517
+ if (!parent) throw new Error("Ancestor repair: missing parent record");
21518
+ const parentInactive = await visit(parentResource, parent);
21519
+ inherited = inherited || parentInactive;
21520
+ }
21521
+ active.delete(key);
21522
+ const effective = inherited || row.isArchived === true || row.trashedAt != null;
21523
+ resolved.set(key, effective);
21524
+ return root ? inherited : effective;
21525
+ }
21526
+ return visit(resource, record, true);
21527
+ }
21528
+
21529
+ // src/execution/migration/ancestor-inactive.ts
21530
+ var DEFAULT_BATCH_SIZE = 500;
21531
+ function compareCodePoints(a, b) {
21532
+ return a < b ? -1 : a > b ? 1 : 0;
21533
+ }
21534
+ function ancestorInactiveResources(schema) {
21535
+ return [...getAncestorInactiveResources(schema.relations)].sort(compareCodePoints);
21536
+ }
21537
+ async function recomputeAncestorInactive(adapter, schema, options) {
21538
+ const { namespace, dryRun = false, logger } = options;
21539
+ const batchSize = options.batchSize ?? DEFAULT_BATCH_SIZE;
21540
+ const maxGraphNodes = options.maxGraphNodes ?? 1e4;
21541
+ for (const value of [batchSize, maxGraphNodes]) {
21542
+ if (!Number.isSafeInteger(value) || value < 1) throw new Error("Ancestor repair: limits must be positive safe integers");
21543
+ }
21544
+ const resources = ancestorInactiveResources(schema);
21545
+ if (resources.length === 0) return { scanned: 0, updated: 0, skipped: 0, nextCursor: null };
21546
+ let cursor = options.cursor ?? { resource: resources[0], afterId: null };
21547
+ let resourceIndex = resources.indexOf(cursor.resource);
21548
+ if (resourceIndex === -1) {
21549
+ throw new Error(`recomputeAncestorInactive: unknown cursor resource "${cursor.resource}"`);
21550
+ }
21551
+ let scanned = 0;
21552
+ let updated = 0;
21553
+ let skipped = 0;
21554
+ let remaining = batchSize;
21555
+ while (remaining > 0) {
21556
+ const resource = resources[resourceIndex];
21557
+ const requested = remaining;
21558
+ const rows = await adapter.findMany({
21559
+ model: resource,
21560
+ where: cursor.afterId === null ? [] : [{ field: "id", operator: "gt", value: cursor.afterId }],
21561
+ orderBy: [{ field: "id", direction: "asc" }],
21562
+ limit: requested,
21563
+ namespace
21564
+ });
21565
+ for (const row of rows) {
21566
+ const id = row.id;
21567
+ if (typeof id !== "string" || id.length === 0) throw new Error("Ancestor repair: malformed record identifier");
21568
+ scanned += 1;
21569
+ const next = await resolveAuthoritativeAncestorInactive(adapter, schema, resource, row, namespace, maxGraphNodes);
21570
+ const previous = row[ANCESTOR_INACTIVE_FIELD];
21571
+ if (previous !== next) {
21572
+ if (dryRun) {
21573
+ updated += 1;
21574
+ } else {
21575
+ const affected = await adapter.updateMany({
21576
+ model: resource,
21577
+ where: [
21578
+ { field: "id", operator: "eq", value: id },
21579
+ {
21580
+ field: ANCESTOR_INACTIVE_FIELD,
21581
+ operator: "eq",
21582
+ value: previous ?? null
21583
+ }
21584
+ ],
21585
+ data: { [ANCESTOR_INACTIVE_FIELD]: next },
21586
+ namespace
21587
+ });
21588
+ updated += affected > 0 ? 1 : 0;
21589
+ skipped += affected > 0 ? 0 : 1;
21590
+ }
21591
+ }
21592
+ cursor = { resource, afterId: id };
21593
+ }
21594
+ remaining -= rows.length;
21595
+ if (rows.length < requested) {
21596
+ resourceIndex += 1;
21597
+ if (resourceIndex >= resources.length) {
21598
+ logger?.info("datafn.ancestorInactive.recompute.complete", { namespace, scanned, updated, skipped, dryRun });
21599
+ return { scanned, updated, skipped, nextCursor: null };
21600
+ }
21601
+ cursor = { resource: resources[resourceIndex], afterId: null };
21602
+ }
21603
+ }
21604
+ return { scanned, updated, skipped, nextCursor: cursor };
21605
+ }
21606
+ async function recomputeAncestorInactiveAll(adapter, schema, options) {
21607
+ const maxSweeps = options.maxSweeps ?? 32;
21608
+ if (!Number.isSafeInteger(maxSweeps) || maxSweeps < 1) throw new Error("Ancestor repair: maxSweeps must be a positive safe integer");
21609
+ let scanned = 0;
21610
+ let updated = 0;
21611
+ let skipped = 0;
21612
+ let sweeps = 0;
21613
+ let converged = false;
21614
+ while (sweeps < maxSweeps) {
21615
+ sweeps += 1;
21616
+ let sweepUpdated = 0;
21617
+ let sweepSkipped = 0;
21618
+ let cursor = null;
21619
+ do {
21620
+ const result = await recomputeAncestorInactive(adapter, schema, { ...options, cursor });
21621
+ scanned += result.scanned;
21622
+ sweepUpdated += result.updated;
21623
+ sweepSkipped += result.skipped;
21624
+ cursor = result.nextCursor;
21625
+ } while (cursor !== null);
21626
+ updated += sweepUpdated;
21627
+ skipped += sweepSkipped;
21628
+ if (sweepUpdated === 0 && sweepSkipped === 0) {
21629
+ converged = true;
21630
+ break;
21631
+ }
21632
+ if (options.dryRun) break;
21633
+ }
21634
+ if (!converged) {
21635
+ options.logger?.warn("datafn.ancestorInactive.recompute.notConverged", {
21636
+ namespace: options.namespace,
21637
+ sweeps,
21638
+ updated,
21639
+ skipped,
21640
+ dryRun: options.dryRun === true
21641
+ });
21642
+ }
21643
+ return { scanned, updated, skipped, sweeps, converged };
21644
+ }
21645
+
21646
+ export { AtomicSequenceStore, ChainedSequenceStore, DATAFN_MULTI_REGION_CAPABILITY, DATAFN_ROUTING_ASSERTION_HEADER, DATAFN_ROUTING_INTERNAL_HEADERS, DatabaseSequenceStore, DatafnExecutorError, DatafnNamespaceStorageError, DatafnPublicLinkInputError, DatafnRoutingError, POSTGRES_NAMESPACE_STORAGE_CATALOG_SQL, POSTGRES_NAMESPACE_STORAGE_INDEX_SQL, ancestorInactiveResources, assertInternalNamespaceStorageMetadataComplete, claimDatafnNamespacePlacement, composeNamespaceStoragePlan, createConditionalKvDatafnPlacementDirectory, createDatafnEd25519RouteTicketSigner, createDatafnEd25519RouteTicketVerifier, createDatafnGatewayRouter, createDatafnHmacRouteTickets, createDatafnHmacRoutingAssertions, createDatafnMultiRegionPlugin, createDatafnPublicLinksPlugin, createDatafnRouteBootstrap, createDatafnServer, createMemoryDatafnPlacementDirectory, createMemoryDatafnRoutingReplayStore, createSequenceStore, datafn, datafnMultiRegionPlugin, drainNamespacePermissionDirectoryOutbox, drainNamespaceStorage, inspectPostgresNamespaceStorage, migrateDatafnNamespace, namespacedInternalTableRoles, quotePostgresIdentifier, rankDatafnPlacementRegions, readDatafnCloudflarePlacementLocation, readDatafnPublicLinkToken, readDatafnRouteTicket, recomputeAncestorInactive, recomputeAncestorInactiveAll, resolveDatafnPublicLink, resolveNamespaceStoragePlan, routeTicketError, selectDatafnPlacementRegion, selectNamespaceStorageEntries, validateDatafnPlacement, validateDatafnRouteTicket, validateDatafnRoutingBodyLimit, verifyDatafnRegionalTicketIdentity, withDatafnPublicLinksSchema, withDatafnRegionalCors, withDatafnRoutingAssertion };
20433
21647
  //# sourceMappingURL=index.js.map
20434
21648
  //# sourceMappingURL=index.js.map