@patodo/localapp 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/.localapp-artifact.json +76 -76
  2. package/README.md +1 -1
  3. package/package.json +1 -1
  4. package/runtime/native/adapter-manifest.json +1 -1
  5. package/runtime/native/win32-x64/localapp-native.exe +0 -0
  6. package/runtime/server/.localapp-server-runtime.json +57 -57
  7. package/runtime/server/bin/worker.cjs +397 -91
  8. package/runtime/server/web/404.html +1 -1
  9. package/runtime/server/web/inbox.html +1 -1
  10. package/runtime/server/web/inbox.txt +1 -1
  11. package/runtime/server/web/index.html +1 -1
  12. package/runtime/server/web/index.txt +1 -1
  13. package/runtime/server/web/my/analytics.html +1 -1
  14. package/runtime/server/web/my/analytics.txt +1 -1
  15. package/runtime/server/web/my/apps/placeholder/settings.html +1 -1
  16. package/runtime/server/web/my/apps/placeholder/settings.txt +1 -1
  17. package/runtime/server/web/my/apps.html +1 -1
  18. package/runtime/server/web/my/apps.txt +1 -1
  19. package/runtime/server/web/my/dashboard.html +1 -1
  20. package/runtime/server/web/my/dashboard.txt +1 -1
  21. package/runtime/server/web/my/device-actions.html +1 -1
  22. package/runtime/server/web/my/device-actions.txt +1 -1
  23. package/runtime/server/web/my/device-notifications.html +1 -1
  24. package/runtime/server/web/my/device-notifications.txt +1 -1
  25. package/runtime/server/web/my/favorites.html +1 -1
  26. package/runtime/server/web/my/favorites.txt +1 -1
  27. package/runtime/server/web/my/groups.html +1 -1
  28. package/runtime/server/web/my/groups.txt +1 -1
  29. package/runtime/server/web/my/info.html +1 -1
  30. package/runtime/server/web/my/info.txt +1 -1
  31. package/runtime/server/web/my/keys.html +1 -1
  32. package/runtime/server/web/my/keys.txt +1 -1
  33. package/runtime/server/web/my/orgs.html +1 -1
  34. package/runtime/server/web/my/orgs.txt +1 -1
  35. package/runtime/server/web/my/pages.html +1 -1
  36. package/runtime/server/web/my/pages.txt +1 -1
  37. package/runtime/server/web/my/peers.html +1 -1
  38. package/runtime/server/web/my/peers.txt +1 -1
  39. package/runtime/server/web/my/recent.html +1 -1
  40. package/runtime/server/web/my/recent.txt +1 -1
  41. package/runtime/server/web/my/settings.html +1 -1
  42. package/runtime/server/web/my/settings.txt +1 -1
  43. package/runtime/server/web/my/studio.html +1 -1
  44. package/runtime/server/web/my/studio.txt +1 -1
  45. package/runtime/server/web/my/subscriptions.html +1 -1
  46. package/runtime/server/web/my/subscriptions.txt +1 -1
  47. package/runtime/server/web/my/system.html +1 -1
  48. package/runtime/server/web/my/system.txt +1 -1
  49. package/runtime/server/web/my/tasks.html +1 -1
  50. package/runtime/server/web/my/tasks.txt +1 -1
  51. package/runtime/server/web/my/users.html +1 -1
  52. package/runtime/server/web/my/users.txt +1 -1
  53. package/runtime/server/web/my.html +1 -1
  54. package/runtime/server/web/my.txt +1 -1
  55. package/runtime/server/web/platform-shell/placeholder/placeholder.html +1 -1
  56. package/runtime/server/web/platform-shell/placeholder/placeholder.txt +1 -1
  57. package/runtime/server/web/platform-shell-preview.html +1 -1
  58. package/runtime/server/web/platform-shell-preview.txt +1 -1
  59. package/runtime/server/web/setup.html +1 -1
  60. package/runtime/server/web/setup.txt +1 -1
  61. package/template/runtime/version.json +1 -1
  62. /package/runtime/server/web/_next/static/{CqtRUQyhpQ2FmEc3vaVz3 → q1M2-7PPyORakTt3WglxD}/_buildManifest.js +0 -0
  63. /package/runtime/server/web/_next/static/{CqtRUQyhpQ2FmEc3vaVz3 → q1M2-7PPyORakTt3WglxD}/_ssgManifest.js +0 -0
@@ -49879,7 +49879,7 @@ var require_issue_templates = __commonJS({
49879
49879
  var MAX_TITLE_PREFIX_LENGTH = 80;
49880
49880
  var MAX_BODY_LENGTH = 2e4;
49881
49881
  var MAX_LABELS = 10;
49882
- function isRecord12(value) {
49882
+ function isRecord13(value) {
49883
49883
  return typeof value === "object" && value !== null && !Array.isArray(value);
49884
49884
  }
49885
49885
  function readString(value, path43, maximum, required2, trim) {
@@ -49896,11 +49896,11 @@ var require_issue_templates = __commonJS({
49896
49896
  return normalized;
49897
49897
  }
49898
49898
  function parseIssueTemplatesConfig3(manifest) {
49899
- if (!isRecord12(manifest))
49899
+ if (!isRecord13(manifest))
49900
49900
  throw new IssueTemplateConfigError2("manifest", "must be an object");
49901
49901
  if (manifest.issues === void 0)
49902
49902
  return [];
49903
- if (!isRecord12(manifest.issues))
49903
+ if (!isRecord13(manifest.issues))
49904
49904
  throw new IssueTemplateConfigError2("issues", "must be an object");
49905
49905
  if (manifest.issues.templates === void 0)
49906
49906
  return [];
@@ -49911,7 +49911,7 @@ var require_issue_templates = __commonJS({
49911
49911
  const seenIds = /* @__PURE__ */ new Set();
49912
49912
  return manifest.issues.templates.map((value, index3) => {
49913
49913
  const basePath = `issues.templates[${index3}]`;
49914
- if (!isRecord12(value))
49914
+ if (!isRecord13(value))
49915
49915
  throw new IssueTemplateConfigError2(basePath, "must be an object");
49916
49916
  const id = readString(value.id, `${basePath}.id`, MAX_ID_LENGTH, true, true);
49917
49917
  if (!TEMPLATE_ID_PATTERN.test(id))
@@ -50761,7 +50761,7 @@ var require_backend_contract = __commonJS({
50761
50761
  });
50762
50762
  }
50763
50763
  function resolveTransactionResultRefs(body, results) {
50764
- if (!isRecord12(body) || !isRecord12(body.params))
50764
+ if (!isRecord13(body) || !isRecord13(body.params))
50765
50765
  return body;
50766
50766
  return {
50767
50767
  ...body,
@@ -50787,22 +50787,22 @@ var require_backend_contract = __commonJS({
50787
50787
  if (Array.isArray(value)) {
50788
50788
  return value.map((item) => resolveTransactionParamValue(item, results));
50789
50789
  }
50790
- if (isRecord12(value)) {
50790
+ if (isRecord13(value)) {
50791
50791
  return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, resolveTransactionParamValue(item, results)]));
50792
50792
  }
50793
50793
  return value;
50794
50794
  }
50795
50795
  function isTransactionResultRef(value) {
50796
- return isRecord12(value) && typeof value.$result === "number" && typeof value.field === "string";
50796
+ return isRecord13(value) && typeof value.$result === "number" && typeof value.field === "string";
50797
50797
  }
50798
50798
  function normalizeNamedSqlTransactionRequest(body, mutations) {
50799
50799
  if (mutations)
50800
50800
  return mutations;
50801
- if (!isRecord12(body) || !Array.isArray(body.mutations)) {
50801
+ if (!isRecord13(body) || !Array.isArray(body.mutations)) {
50802
50802
  throw new Error("Named SQL transaction body must include mutations array");
50803
50803
  }
50804
50804
  return body.mutations.map((item, index3) => {
50805
- if (!isRecord12(item) || typeof item.name !== "string" || !item.name.trim()) {
50805
+ if (!isRecord13(item) || typeof item.name !== "string" || !item.name.trim()) {
50806
50806
  throw new Error(`Named SQL transaction mutation at index ${index3} must declare name`);
50807
50807
  }
50808
50808
  if ("sql" in item) {
@@ -50810,7 +50810,7 @@ var require_backend_contract = __commonJS({
50810
50810
  }
50811
50811
  return {
50812
50812
  name: item.name,
50813
- body: "body" in item ? item.body : { params: isRecord12(item.params) ? item.params : {} }
50813
+ body: "body" in item ? item.body : { params: isRecord13(item.params) ? item.params : {} }
50814
50814
  };
50815
50815
  });
50816
50816
  }
@@ -50968,13 +50968,13 @@ var require_backend_contract = __commonJS({
50968
50968
  if (typeof value.name !== "string" || !value.name.trim()) {
50969
50969
  throw new Error(`Resource schema must declare name: ${file.relativePath}`);
50970
50970
  }
50971
- if (value.fields !== void 0 && !isRecord12(value.fields)) {
50971
+ if (value.fields !== void 0 && !isRecord13(value.fields)) {
50972
50972
  throw new Error(`Resource schema must declare fields: ${file.relativePath}`);
50973
50973
  }
50974
50974
  if (contract.resources[value.name]) {
50975
50975
  throw new Error(`Duplicate resource schema name: ${value.name}`);
50976
50976
  }
50977
- const schema = { ...value, fields: isRecord12(value.fields) ? value.fields : {} };
50977
+ const schema = { ...value, fields: isRecord13(value.fields) ? value.fields : {} };
50978
50978
  contract.resources[value.name] = {
50979
50979
  schema,
50980
50980
  schemaFile: file
@@ -50986,11 +50986,11 @@ var require_backend_contract = __commonJS({
50986
50986
  if (file.schemaUrl !== expectedSchema) {
50987
50987
  throw new Error(`${containerName} file uses the wrong $schema: ${file.relativePath}`);
50988
50988
  }
50989
- if (!isRecord12(value[containerName])) {
50989
+ if (!isRecord13(value[containerName])) {
50990
50990
  throw new Error(`${containerName} file must declare ${containerName}: ${file.relativePath}`);
50991
50991
  }
50992
50992
  for (const [name, rawEntry] of Object.entries(value[containerName])) {
50993
- if (!isRecord12(rawEntry)) {
50993
+ if (!isRecord13(rawEntry)) {
50994
50994
  throw new Error(`Named SQL entry must be an object: ${name}`);
50995
50995
  }
50996
50996
  if (target[name]) {
@@ -51004,7 +51004,7 @@ var require_backend_contract = __commonJS({
51004
51004
  throw new Error(`Named SQL ${name} must declare sql`);
51005
51005
  }
51006
51006
  const params = rawEntry.params === void 0 ? {} : rawEntry.params;
51007
- if (!isRecord12(params)) {
51007
+ if (!isRecord13(params)) {
51008
51008
  throw new Error(`Named SQL ${name} params must be an object`);
51009
51009
  }
51010
51010
  const access = isAccessLevel(rawEntry.access) ? rawEntry.access : void 0;
@@ -51040,7 +51040,7 @@ var require_backend_contract = __commonJS({
51040
51040
  function parseNamedSqlSecurity(value, input) {
51041
51041
  if (value === void 0)
51042
51042
  return void 0;
51043
- if (!isRecord12(value))
51043
+ if (!isRecord13(value))
51044
51044
  throw new Error(`Named SQL ${input.name} security must be an object`);
51045
51045
  if (value.mode === "generated")
51046
51046
  return parseGeneratedSecurity(value, input);
@@ -51051,7 +51051,7 @@ var require_backend_contract = __commonJS({
51051
51051
  function parseGeneratedSecurity(value, input) {
51052
51052
  const template = requiredSecurityString(value, "template", input.name);
51053
51053
  const resource = requiredSecurityIdentifier(value, "resource", input.name);
51054
- if (!isRecord12(value.config)) {
51054
+ if (!isRecord13(value.config)) {
51055
51055
  throw new Error(`Named SQL ${input.name} generated security must declare config`);
51056
51056
  }
51057
51057
  const digest2 = requiredSecurityString(value, "digest", input.name);
@@ -51158,7 +51158,7 @@ var require_backend_contract = __commonJS({
51158
51158
  throw new Error(`Named SQL ${input.name} custom security must declare scenarios`);
51159
51159
  }
51160
51160
  const scenarios = value.scenarios.map((scenario) => {
51161
- if (!isRecord12(scenario)) {
51161
+ if (!isRecord13(scenario)) {
51162
51162
  throw new Error(`Named SQL ${input.name} custom security scenario must be an object`);
51163
51163
  }
51164
51164
  const identity = requiredSecurityString(scenario, "identity", input.name);
@@ -51189,7 +51189,7 @@ var require_backend_contract = __commonJS({
51189
51189
  function canonicalSecurityJson(value) {
51190
51190
  if (Array.isArray(value))
51191
51191
  return `[${value.map(canonicalSecurityJson).join(",")}]`;
51192
- if (isRecord12(value)) {
51192
+ if (isRecord13(value)) {
51193
51193
  return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalSecurityJson(value[key])}`).join(",")}}`;
51194
51194
  }
51195
51195
  return JSON.stringify(value);
@@ -51246,7 +51246,7 @@ var require_backend_contract = __commonJS({
51246
51246
  function parseNamedSqlResult(value, name) {
51247
51247
  if (value === void 0)
51248
51248
  return void 0;
51249
- if (!isRecord12(value))
51249
+ if (!isRecord13(value))
51250
51250
  throw new Error(`Named SQL ${name} result must be an object`);
51251
51251
  const mode = value.mode;
51252
51252
  if (mode !== "page" && mode !== "single" && mode !== "aggregate" && mode !== "bounded") {
@@ -51327,7 +51327,7 @@ var require_backend_contract = __commonJS({
51327
51327
  }
51328
51328
  }
51329
51329
  function normalizeNamedSqlRequest(body) {
51330
- if (!isRecord12(body)) {
51330
+ if (!isRecord13(body)) {
51331
51331
  return { params: {} };
51332
51332
  }
51333
51333
  if ("sql" in body) {
@@ -51336,7 +51336,7 @@ var require_backend_contract = __commonJS({
51336
51336
  if (body.params === void 0) {
51337
51337
  return { params: {} };
51338
51338
  }
51339
- if (!isRecord12(body.params)) {
51339
+ if (!isRecord13(body.params)) {
51340
51340
  throw new Error("Named SQL params must be an object");
51341
51341
  }
51342
51342
  return { params: body.params };
@@ -51659,7 +51659,7 @@ var require_backend_contract = __commonJS({
51659
51659
  const relative = node_path_1.default.relative(node_path_1.default.resolve(root5), node_path_1.default.resolve(candidate));
51660
51660
  return relative === "" || !relative.startsWith("..") && !node_path_1.default.isAbsolute(relative);
51661
51661
  }
51662
- function isRecord12(value) {
51662
+ function isRecord13(value) {
51663
51663
  return typeof value === "object" && value !== null && !Array.isArray(value);
51664
51664
  }
51665
51665
  function isAccessLevel(value) {
@@ -51923,7 +51923,7 @@ var require_backend_actions = __commonJS({
51923
51923
  return parseActionManifest(value);
51924
51924
  }
51925
51925
  function parseActionManifest(value) {
51926
- if (!isRecord12(value))
51926
+ if (!isRecord13(value))
51927
51927
  throw new Error("Action manifest must be an object");
51928
51928
  if (value.version !== 1)
51929
51929
  throw new Error("Action manifest version must be 1");
@@ -51984,7 +51984,7 @@ var require_backend_actions = __commonJS({
51984
51984
  function validateActionInput(action, input) {
51985
51985
  const schema = action.input ?? { type: "object" };
51986
51986
  validateValue(`${action.name}.input`, schema, input);
51987
- return isRecord12(input) ? input : {};
51987
+ return isRecord13(input) ? input : {};
51988
51988
  }
51989
51989
  function createActionContext(options2) {
51990
51990
  return {
@@ -52368,7 +52368,7 @@ var require_backend_actions = __commonJS({
52368
52368
  });
52369
52369
  }
52370
52370
  function asParams(value) {
52371
- return isRecord12(value) ? value : void 0;
52371
+ return isRecord13(value) ? value : void 0;
52372
52372
  }
52373
52373
  function serializeActionError(err) {
52374
52374
  return {
@@ -52380,12 +52380,12 @@ var require_backend_actions = __commonJS({
52380
52380
  };
52381
52381
  }
52382
52382
  function deserializeActionError(value) {
52383
- if (isRecord12(value)) {
52383
+ if (isRecord13(value)) {
52384
52384
  const message = typeof value.message === "string" ? value.message : "Action execution failed";
52385
52385
  const status = typeof value.status === "number" ? value.status : void 0;
52386
52386
  const name = typeof value.name === "string" ? value.name : "";
52387
52387
  const code = typeof value.code === "string" ? value.code : void 0;
52388
- const details = isRecord12(value.details) ? value.details : void 0;
52388
+ const details = isRecord13(value.details) ? value.details : void 0;
52389
52389
  if (code === "action_resource_limit" || name === "DataCloneError" || /could not be cloned/i.test(message)) {
52390
52390
  return new ActionError("Action worker failed to serialize result", 500, {
52391
52391
  code: "action_resource_limit",
@@ -52507,7 +52507,7 @@ var require_backend_actions = __commonJS({
52507
52507
  });
52508
52508
  }
52509
52509
  function countRows(value) {
52510
- if (isRecord12(value) && Array.isArray(value.rows))
52510
+ if (isRecord13(value) && Array.isArray(value.rows))
52511
52511
  return value.rows.length;
52512
52512
  return 0;
52513
52513
  }
@@ -52650,7 +52650,7 @@ function makeCtx() {
52650
52650
  })();
52651
52651
  `;
52652
52652
  function parseActionEntry(value, index3) {
52653
- if (!isRecord12(value))
52653
+ if (!isRecord13(value))
52654
52654
  throw new Error(`Action entry at index ${index3} must be an object`);
52655
52655
  if (typeof value.name !== "string" || !value.name.trim())
52656
52656
  throw new Error(`Action entry at index ${index3} must declare name`);
@@ -52662,7 +52662,7 @@ function makeCtx() {
52662
52662
  type: value.type === void 0 || value.type === "command" ? value.type : value.type,
52663
52663
  access: isAccessLevel(value.access) ? value.access : value.access === void 0 ? void 0 : value.access,
52664
52664
  input: value.input === void 0 ? { type: "object" } : value.input,
52665
- uses: isRecord12(value.uses) ? {
52665
+ uses: isRecord13(value.uses) ? {
52666
52666
  queries: parseStringArray(value.uses.queries, `Action ${value.name} uses.queries`),
52667
52667
  mutations: parseStringArray(value.uses.mutations, `Action ${value.name} uses.mutations`)
52668
52668
  } : void 0
@@ -52687,7 +52687,7 @@ function makeCtx() {
52687
52687
  throw new Error(`Invalid action input schema at ${label}: required must be string[]`);
52688
52688
  }
52689
52689
  if (schema.properties !== void 0) {
52690
- if (!isRecord12(schema.properties))
52690
+ if (!isRecord13(schema.properties))
52691
52691
  throw new Error(`Invalid action input schema at ${label}: properties must be an object`);
52692
52692
  for (const [key, child] of Object.entries(schema.properties))
52693
52693
  validateSchemaNode(`${label}.${key}`, child);
@@ -52707,7 +52707,7 @@ function makeCtx() {
52707
52707
  case "unknown":
52708
52708
  return;
52709
52709
  case "object": {
52710
- if (!isRecord12(value))
52710
+ if (!isRecord13(value))
52711
52711
  throw new ActionError(`${label} must be an object`, 400);
52712
52712
  const required2 = schema.required ?? [];
52713
52713
  for (const key of required2) {
@@ -52773,7 +52773,7 @@ function makeCtx() {
52773
52773
  const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "\0").replace(/\*/g, "[^/]*").replace(/\u0000/g, ".*");
52774
52774
  return new RegExp(`^${escaped}$`).test(candidate);
52775
52775
  }
52776
- function isRecord12(value) {
52776
+ function isRecord13(value) {
52777
52777
  return typeof value === "object" && value !== null && !Array.isArray(value);
52778
52778
  }
52779
52779
  }
@@ -134540,12 +134540,6 @@ async function computeSchemaFingerprint(dbPath2) {
134540
134540
  }
134541
134541
  }
134542
134542
  async function validateCandidateSchema(input) {
134543
- if (input.archiveVersion > input.currentVersion) {
134544
- throw new AppDataError("APP_ARCHIVE_VERSION_TOO_NEW", "Data archive was created by a newer application version");
134545
- }
134546
- if (input.archiveVersion < input.currentVersion) {
134547
- await (0, import_server_core8.applyPendingMigrations)({ dbPath: input.candidatePath, migrationsDir: input.migrationsDir });
134548
- }
134549
134543
  const referencePath = import_node_path25.default.join(import_node_path25.default.dirname(input.candidatePath), `.schema-reference-${import_node_crypto19.default.randomUUID()}.db`);
134550
134544
  try {
134551
134545
  await (0, import_server_core8.applyPendingMigrations)({ dbPath: referencePath, migrationsDir: input.migrationsDir });
@@ -134671,6 +134665,7 @@ async function createDataArchive(input) {
134671
134665
  files.push({
134672
134666
  path: entryPath,
134673
134667
  objectKey,
134668
+ ...objectKey !== object.key ? { sourceObjectKey: object.key } : {},
134674
134669
  ...stored.contentType || object.contentType ? { contentType: stored.contentType ?? object.contentType } : {},
134675
134670
  size: actualSize,
134676
134671
  sha256: hash2.digest("hex")
@@ -134681,6 +134676,7 @@ async function createDataArchive(input) {
134681
134676
  formatVersion: 1,
134682
134677
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
134683
134678
  application: input.application,
134679
+ ...sourceApplication.owner !== input.application.owner || sourceApplication.name !== input.application.name ? { sourceApplication } : {},
134684
134680
  database: databaseEntry,
134685
134681
  files
134686
134682
  };
@@ -134821,9 +134817,6 @@ async function extractAndValidateDataArchive(input) {
134821
134817
  if (manifest.application.owner !== input.expectedApplication.owner || manifest.application.name !== input.expectedApplication.name) {
134822
134818
  throw new AppDataError("APP_ARCHIVE_IDENTITY_MISMATCH", "Data archive belongs to another application");
134823
134819
  }
134824
- if (manifest.application.version > input.expectedApplication.maxVersion) {
134825
- throw new AppDataError("APP_ARCHIVE_VERSION_TOO_NEW", "Data archive was created by a newer application version");
134826
- }
134827
134820
  if (manifest.database.path !== "database/app.db") {
134828
134821
  throw new AppDataError("APP_ARCHIVE_MANIFEST_INVALID", "Archive database path is invalid");
134829
134822
  }
@@ -134839,12 +134832,23 @@ async function extractAndValidateDataArchive(input) {
134839
134832
  throw new AppDataError("APP_ARCHIVE_OBJECT_KEY_INVALID", `Archive object mapping is invalid: ${file.objectKey}`);
134840
134833
  }
134841
134834
  if (objectKeys.has(file.objectKey)) throw new AppDataError("APP_ARCHIVE_MANIFEST_INVALID", `Duplicate object key: ${file.objectKey}`);
134835
+ if (file.sourceObjectKey !== void 0) {
134836
+ const source = manifest.sourceApplication;
134837
+ if (!source || !appObjectKeyAllowed(file.sourceObjectKey, source.owner, source.name)) {
134838
+ throw new AppDataError("APP_ARCHIVE_OBJECT_KEY_INVALID", `Archive source object mapping is invalid: ${file.sourceObjectKey}`);
134839
+ }
134840
+ }
134842
134841
  if (filePaths.has(file.path)) throw new AppDataError("APP_ARCHIVE_MANIFEST_INVALID", `Duplicate file path: ${file.path}`);
134843
134842
  objectKeys.add(file.objectKey);
134844
134843
  filePaths.add(file.path);
134845
134844
  expectedEntries.add(file.path);
134846
134845
  const entry = assertEntryMatches(extracted.get(file.path), file, file.path);
134847
- return { path: entry.path, objectKey: file.objectKey, ...file.contentType ? { contentType: file.contentType } : {} };
134846
+ return {
134847
+ path: entry.path,
134848
+ objectKey: file.objectKey,
134849
+ ...file.sourceObjectKey ? { sourceObjectKey: file.sourceObjectKey } : {},
134850
+ ...file.contentType ? { contentType: file.contentType } : {}
134851
+ };
134848
134852
  });
134849
134853
  for (const entryName of extracted.keys()) {
134850
134854
  if (!expectedEntries.has(entryName)) throw new AppDataError("APP_ARCHIVE_UNDECLARED_ENTRY", `Archive entry is not declared: ${entryName}`);
@@ -134889,7 +134893,7 @@ async function currentMigrationsDir(pageDir, application) {
134889
134893
  throw error5;
134890
134894
  }
134891
134895
  }
134892
- function isBackupId(id) {
134896
+ function isAppBackupId(id) {
134893
134897
  return /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(id);
134894
134898
  }
134895
134899
  function atomicWrite(filePath, bytes) {
@@ -134918,19 +134922,88 @@ function inferAppDataIdentity(pageDir) {
134918
134922
  }
134919
134923
  async function createArchiveAt(input) {
134920
134924
  (0, app_db_exports.closeConnectionsForPage)(input.pageDir);
134921
- const databasePath = import_node_path27.default.join(input.pageDir, "app.db");
134922
- if (!import_node_fs20.default.existsSync(databasePath)) throw new AppDataError("APP_DATABASE_NOT_FOUND", "Application database does not exist");
134925
+ const sourceDatabasePath = import_node_path27.default.join(input.pageDir, "app.db");
134926
+ if (!import_node_fs20.default.existsSync(sourceDatabasePath)) throw new AppDataError("APP_DATABASE_NOT_FOUND", "Application database does not exist");
134923
134927
  const sourceApplication = input.sourceApplication ?? input.application;
134924
134928
  const objects = await input.storage.listAppObjects(sourceApplication.owner, sourceApplication.name);
134925
- return createDataArchive({
134926
- outputPath: input.outputPath,
134927
- databasePath,
134928
- application: input.application,
134929
- sourceApplication,
134930
- objects,
134931
- openObject: input.storage.openObject,
134932
- limits: input.limits
134933
- });
134929
+ const crossOwner = sourceApplication.owner !== input.application.owner || sourceApplication.name !== input.application.name;
134930
+ const databasePath = crossOwner ? import_node_path27.default.join(operationDir(input.pageDir), `export-database-${import_node_crypto21.default.randomUUID()}.db`) : sourceDatabasePath;
134931
+ try {
134932
+ if (crossOwner) {
134933
+ import_node_fs20.default.copyFileSync(sourceDatabasePath, databasePath);
134934
+ await rebaseDatabaseReferences(databasePath, {
134935
+ sourceApplication,
134936
+ targetApplication: input.application,
134937
+ objectMappings: objects.map((object) => ({
134938
+ source: object.key,
134939
+ target: rebaseObjectKey(object.key, sourceApplication, input.application)
134940
+ })),
134941
+ identityColumns: declaredIdentityColumns(input.pageDir, input.application.version)
134942
+ });
134943
+ }
134944
+ return await createDataArchive({
134945
+ outputPath: input.outputPath,
134946
+ databasePath,
134947
+ application: input.application,
134948
+ sourceApplication,
134949
+ objects,
134950
+ openObject: input.storage.openObject,
134951
+ limits: input.limits
134952
+ });
134953
+ } finally {
134954
+ if (crossOwner) import_node_fs20.default.rmSync(databasePath, { force: true });
134955
+ }
134956
+ }
134957
+ function rebaseObjectKey(key, source, target) {
134958
+ const appPrefix = `${source.owner}/${source.name}/`;
134959
+ const issuePrefix = `issues/${source.owner}/${source.name}/`;
134960
+ if (key.startsWith(appPrefix)) return `${target.owner}/${target.name}/${key.slice(appPrefix.length)}`;
134961
+ if (key.startsWith(issuePrefix)) return `issues/${target.owner}/${target.name}/${key.slice(issuePrefix.length)}`;
134962
+ throw new AppDataError("APP_ARCHIVE_OBJECT_KEY_INVALID", `Object key is outside the application namespace: ${key}`);
134963
+ }
134964
+ function declaredIdentityColumns(pageDir, version) {
134965
+ const resourcesDir = import_node_path27.default.join(pageDir, "versions", `v${version}`, "backend", "resources");
134966
+ if (!import_node_fs20.default.existsSync(resourcesDir)) return [];
134967
+ const result = /* @__PURE__ */ new Map();
134968
+ for (const entry of import_node_fs20.default.readdirSync(resourcesDir, { withFileTypes: true })) {
134969
+ if (!entry.isDirectory()) continue;
134970
+ const resourceDir = import_node_path27.default.join(resourcesDir, entry.name);
134971
+ const schemaPath = import_node_path27.default.join(resourceDir, "schema.json");
134972
+ try {
134973
+ const schema = JSON.parse(import_node_fs20.default.readFileSync(schemaPath, "utf8"));
134974
+ if (typeof schema.name !== "string") throw new Error("resource name is missing");
134975
+ const ownerField = typeof schema.business?.ownerField === "string" ? schema.business.ownerField : void 0;
134976
+ if (ownerField) result.set(`${schema.name}\0${ownerField}`, { table: schema.name, column: ownerField });
134977
+ for (const contractName of ["queries.json", "mutations.json"]) {
134978
+ const contractPath = import_node_path27.default.join(resourceDir, contractName);
134979
+ if (!import_node_fs20.default.existsSync(contractPath)) continue;
134980
+ const contract = JSON.parse(import_node_fs20.default.readFileSync(contractPath, "utf8"));
134981
+ const definitions = contract[contractName === "queries.json" ? "queries" : "mutations"];
134982
+ if (!definitions || typeof definitions !== "object" || Array.isArray(definitions)) continue;
134983
+ for (const definition2 of Object.values(definitions)) {
134984
+ if (!definition2 || typeof definition2 !== "object" || Array.isArray(definition2)) continue;
134985
+ const record = definition2;
134986
+ const security = record.security && typeof record.security === "object" && !Array.isArray(record.security) ? record.security : {};
134987
+ const config = security.config && typeof security.config === "object" && !Array.isArray(security.config) ? security.config : {};
134988
+ if (security.mode === "generated" && typeof config.identityField === "string") {
134989
+ result.set(`${schema.name}\0${config.identityField}`, { table: schema.name, column: config.identityField });
134990
+ }
134991
+ const systemParams = Array.isArray(security.systemParams) ? security.systemParams : [];
134992
+ const dependsOnCurrentUser = systemParams.includes("currentUserId") || typeof record.sql === "string" && record.sql.includes(":currentUserId");
134993
+ if (security.mode === "custom" && dependsOnCurrentUser && !ownerField) {
134994
+ throw new AppDataError(
134995
+ "APP_DATA_IDENTITY_CONTRACT_REQUIRED",
134996
+ `Resource ${schema.name} must declare business.ownerField before cross-owner data synchronization`
134997
+ );
134998
+ }
134999
+ }
135000
+ }
135001
+ } catch (error5) {
135002
+ if (error5 instanceof AppDataError) throw error5;
135003
+ throw new AppDataError("APP_DATA_IDENTITY_CONTRACT_INVALID", `Cannot read identity contract for resource ${entry.name}`);
135004
+ }
135005
+ }
135006
+ return [...result.values()];
134934
135007
  }
134935
135008
  async function createManagedBackupUnlocked(input) {
134936
135009
  const id = import_node_crypto21.default.randomUUID();
@@ -134957,7 +135030,7 @@ async function createManagedBackupUnlocked(input) {
134957
135030
  return backup;
134958
135031
  }
134959
135032
  function readBackupMetadata(pageDir, id) {
134960
- if (!isBackupId(id)) return null;
135033
+ if (!isAppBackupId(id)) return null;
134961
135034
  const metaPath = backupMetaPath(pageDir, id);
134962
135035
  if (!import_node_fs20.default.existsSync(metaPath)) return null;
134963
135036
  try {
@@ -135023,17 +135096,114 @@ async function prepareArchive(input) {
135023
135096
  const prepared = await extractAndValidateDataArchive({
135024
135097
  archivePath: input.archivePath,
135025
135098
  stagingDir: input.stagingDir,
135026
- expectedApplication: { owner: input.application.owner, name: input.application.name, maxVersion: input.application.version },
135099
+ expectedApplication: { owner: input.application.owner, name: input.application.name },
135027
135100
  limits: input.limits
135028
135101
  });
135102
+ await rebaseCandidateDatabase(prepared.databasePath, prepared.manifest, declaredIdentityColumns(input.pageDir, input.application.version));
135029
135103
  await validateCandidateSchema({
135030
135104
  candidatePath: prepared.databasePath,
135031
- migrationsDir: await currentMigrationsDir(input.pageDir, input.application),
135032
- archiveVersion: prepared.manifest.application.version,
135033
- currentVersion: input.application.version
135105
+ migrationsDir: await currentMigrationsDir(input.pageDir, input.application)
135034
135106
  });
135035
135107
  return prepared;
135036
135108
  }
135109
+ async function rebaseCandidateDatabase(databasePath, manifest, identityColumns) {
135110
+ const source = manifest.sourceApplication ?? manifest.application;
135111
+ const target = manifest.application;
135112
+ if (source.owner === target.owner && source.name === target.name && identityColumns.length === 0) return;
135113
+ await rebaseDatabaseReferences(databasePath, {
135114
+ sourceApplication: source,
135115
+ targetApplication: target,
135116
+ objectMappings: manifest.files.flatMap((file) => file.sourceObjectKey ? [{ source: file.sourceObjectKey, target: file.objectKey }] : []),
135117
+ identityColumns
135118
+ });
135119
+ }
135120
+ async function rebaseDatabaseReferences(databasePath, input) {
135121
+ const replacements = /* @__PURE__ */ new Map();
135122
+ for (const mapping of input.objectMappings) {
135123
+ replacements.set(mapping.source, mapping.target);
135124
+ const sourcePrefix = `${input.sourceApplication.owner}/${input.sourceApplication.name}/`;
135125
+ const targetPrefix = `${input.targetApplication.owner}/${input.targetApplication.name}/`;
135126
+ if (mapping.source.startsWith(sourcePrefix) && mapping.target.startsWith(targetPrefix)) {
135127
+ replacements.set(
135128
+ `/serve/${sourcePrefix}api/content/${mapping.source.slice(sourcePrefix.length)}`,
135129
+ `/serve/${targetPrefix}api/content/${mapping.target.slice(targetPrefix.length)}`
135130
+ );
135131
+ }
135132
+ }
135133
+ const SQL = await (0, import_sql3.default)();
135134
+ const db2 = new SQL.Database(import_node_fs20.default.readFileSync(databasePath));
135135
+ try {
135136
+ const result = db2.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'");
135137
+ const tables = (result[0]?.values ?? []).map((row) => String(row[0]));
135138
+ db2.run("BEGIN IMMEDIATE");
135139
+ try {
135140
+ for (const table of tables) {
135141
+ const columns = db2.exec(`PRAGMA table_info(${quoteSqlIdentifier(table)})`)[0]?.values ?? [];
135142
+ for (const column of columns) {
135143
+ const name = String(column[1]);
135144
+ const declaredType = String(column[2]).toUpperCase();
135145
+ if (declaredType.length > 0 && !declaredType.includes("TEXT") && !declaredType.includes("CHAR") && !declaredType.includes("CLOB")) continue;
135146
+ const tableId = quoteSqlIdentifier(table);
135147
+ const columnId = quoteSqlIdentifier(name);
135148
+ const values = db2.exec(`SELECT DISTINCT ${columnId} FROM ${tableId} WHERE typeof(${columnId}) = 'text'`)[0]?.values ?? [];
135149
+ for (const row of values) {
135150
+ const current = String(row[0]);
135151
+ const next = rebaseTextValue(current, replacements);
135152
+ if (next !== current) db2.run(`UPDATE ${tableId} SET ${columnId} = ? WHERE ${columnId} = ?`, [next, current]);
135153
+ }
135154
+ }
135155
+ }
135156
+ for (const identity of input.identityColumns) {
135157
+ const tableId = quoteSqlIdentifier(identity.table);
135158
+ const columnId = quoteSqlIdentifier(identity.column);
135159
+ db2.run(`UPDATE ${tableId} SET ${columnId} = ? WHERE ${columnId} IS NOT NULL`, [input.targetApplication.owner]);
135160
+ }
135161
+ db2.run("COMMIT");
135162
+ } catch (error5) {
135163
+ db2.run("ROLLBACK");
135164
+ throw error5;
135165
+ }
135166
+ import_node_fs20.default.writeFileSync(databasePath, Buffer.from(db2.export()), { mode: 384 });
135167
+ } finally {
135168
+ db2.close();
135169
+ }
135170
+ }
135171
+ function rebaseTextValue(value, replacements) {
135172
+ const exact = replacements.get(value);
135173
+ if (exact !== void 0) return exact;
135174
+ const candidate = value.trimStart();
135175
+ if (!candidate.startsWith("{") && !candidate.startsWith("[")) return value;
135176
+ try {
135177
+ const parsed = JSON.parse(candidate);
135178
+ const rebased = rebaseJsonValue(parsed, replacements);
135179
+ return rebased.changed ? JSON.stringify(rebased.value) : value;
135180
+ } catch {
135181
+ return value;
135182
+ }
135183
+ }
135184
+ function rebaseJsonValue(value, replacements) {
135185
+ if (typeof value === "string") {
135186
+ const next = replacements.get(value);
135187
+ return next === void 0 ? { value, changed: false } : { value: next, changed: true };
135188
+ }
135189
+ if (Array.isArray(value)) {
135190
+ const children = value.map((entry) => rebaseJsonValue(entry, replacements));
135191
+ return { value: children.map((entry) => entry.value), changed: children.some((entry) => entry.changed) };
135192
+ }
135193
+ if (value && typeof value === "object") {
135194
+ let changed = false;
135195
+ const entries = Object.entries(value).map(([key, entry]) => {
135196
+ const child = rebaseJsonValue(entry, replacements);
135197
+ changed ||= child.changed;
135198
+ return [key, child.value];
135199
+ });
135200
+ return { value: Object.fromEntries(entries), changed };
135201
+ }
135202
+ return { value, changed: false };
135203
+ }
135204
+ function quoteSqlIdentifier(value) {
135205
+ return `"${value.replaceAll('"', '""')}"`;
135206
+ }
135037
135207
  async function createAppDataExport(input) {
135038
135208
  const limits = input.limits ?? DEFAULT_ARCHIVE_LIMITS;
135039
135209
  const storage2 = input.storage ?? defaultStorage;
@@ -135071,7 +135241,7 @@ async function importAppData(input) {
135071
135241
  const rollbackDir = import_node_path27.default.join(operationDir(input.pageDir), `rollback-${token}`);
135072
135242
  try {
135073
135243
  const prepared = await prepareArchive({ ...input, limits, stagingDir });
135074
- const safety = await createManagedBackupUnlocked({
135244
+ const safety = input.safetyBackupId ? readBackupMetadata(input.pageDir, input.safetyBackupId) : await createManagedBackupUnlocked({
135075
135245
  pageDir: input.pageDir,
135076
135246
  application: input.application,
135077
135247
  limits,
@@ -135079,6 +135249,7 @@ async function importAppData(input) {
135079
135249
  source: "automatic",
135080
135250
  reason: input.reason
135081
135251
  });
135252
+ if (!safety) throw new AppDataError("APP_BACKUP_NOT_FOUND", "Safety backup not found");
135082
135253
  try {
135083
135254
  await applyPreparedData({ ...input, ...prepared, storage: storage2 });
135084
135255
  } catch (caught) {
@@ -135134,6 +135305,37 @@ async function restoreAppBackup(pageDir, id, options2 = {}) {
135134
135305
  }
135135
135306
  await replaceAppDatabase(pageDir, import_node_fs20.default.readFileSync(getAppBackupPath(pageDir, id)), `restore:${id}`, { ...options2, application });
135136
135307
  }
135308
+ async function restoreAppBackupExact(pageDir, id, options2) {
135309
+ const backup = getAppBackup(pageDir, id);
135310
+ const limits = options2.limits ?? DEFAULT_ARCHIVE_LIMITS;
135311
+ const storage2 = options2.storage ?? defaultStorage;
135312
+ await withAppDataMaintenance(pageDir, async () => {
135313
+ if (backup.format === "legacy-db") {
135314
+ const bytes = import_node_fs20.default.readFileSync(getAppBackupPath(pageDir, id));
135315
+ await validateSqlite(bytes);
135316
+ const candidatePath = import_node_path27.default.join(operationDir(pageDir), `exact-restore-${import_node_crypto21.default.randomUUID()}.db`);
135317
+ try {
135318
+ import_node_fs20.default.writeFileSync(candidatePath, bytes, { mode: 384 });
135319
+ swapDatabaseFile(pageDir, candidatePath);
135320
+ } finally {
135321
+ import_node_fs20.default.rmSync(candidatePath, { force: true });
135322
+ }
135323
+ return;
135324
+ }
135325
+ const stagingDir = import_node_path27.default.join(operationDir(pageDir), `exact-restore-${import_node_crypto21.default.randomUUID()}`);
135326
+ try {
135327
+ const prepared = await extractAndValidateDataArchive({
135328
+ archivePath: getAppBackupPath(pageDir, id),
135329
+ stagingDir,
135330
+ expectedApplication: { owner: options2.application.owner, name: options2.application.name },
135331
+ limits
135332
+ });
135333
+ await applyPreparedData({ pageDir, application: options2.application, ...prepared, storage: storage2 });
135334
+ } finally {
135335
+ import_node_fs20.default.rmSync(stagingDir, { recursive: true, force: true });
135336
+ }
135337
+ });
135338
+ }
135137
135339
  async function validateSqlite(bytes) {
135138
135340
  if (bytes.subarray(0, 16).toString("binary") !== "SQLite format 3\0") throw new AppDataError("APP_DATABASE_INVALID", "File is not a SQLite database");
135139
135341
  const SQL = await (0, import_sql3.default)();
@@ -141653,7 +141855,8 @@ var PeerStore = class {
141653
141855
  baseUrl: peer.baseUrl,
141654
141856
  apiKey: this.secretBox.open(peer.credential, peer.id),
141655
141857
  connectionVersion: peer.connectionVersion,
141656
- verifiedUserId: peer.verifiedUserId
141858
+ verifiedUserId: peer.verifiedUserId,
141859
+ protocolVersion: peer.protocolVersion
141657
141860
  } : null;
141658
141861
  }
141659
141862
  recordVerification(target, verification2) {
@@ -141831,7 +142034,7 @@ function peerError(reply, error5) {
141831
142034
 
141832
142035
  // packages/server/src/routes/peer-protocol.ts
141833
142036
  init_meta_sqlite();
141834
- var PROTOCOL_VERSION = 1;
142037
+ var PEER_PROTOCOL_VERSION = 2;
141835
142038
  async function peerProtocolRoutes(app) {
141836
142039
  app.get("/api/peer/capabilities", async (req, reply) => {
141837
142040
  const authorization = req.headers.authorization;
@@ -141843,7 +142046,7 @@ async function peerProtocolRoutes(app) {
141843
142046
  return {
141844
142047
  success: true,
141845
142048
  data: {
141846
- protocolVersion: PROTOCOL_VERSION,
142049
+ protocolVersion: PEER_PROTOCOL_VERSION,
141847
142050
  user: { id: user.id, name: user.name, displayName: user.displayName },
141848
142051
  transferLimits: { maxPackageBytes: MAX_APP_PACKAGE_BYTES }
141849
142052
  }
@@ -142248,11 +142451,11 @@ var SyncJobStore = class {
142248
142451
  flushMetaDb();
142249
142452
  return required(this.get(id));
142250
142453
  }
142251
- transition(id, status, error5) {
142454
+ transition(id, status, error5, backupId) {
142252
142455
  const current = required(this.get(id));
142253
142456
  if (TERMINAL2.has(current.status)) return current;
142254
142457
  const now = (/* @__PURE__ */ new Date()).toISOString();
142255
- const history = [...current.history, { status, at: now, ...error5 ? { error: error5 } : {} }];
142458
+ const history = [...current.history, { status, at: now, ...error5 ? { error: error5 } : {}, ...backupId ? { backupId } : {} }];
142256
142459
  getDb().run(
142257
142460
  "UPDATE sync_jobs SET status = ?, history_json = ?, error = ?, updated_at = ?, completed_at = ? WHERE id = ?",
142258
142461
  [status, JSON.stringify(history), error5 ?? null, now, TERMINAL2.has(status) ? now : null, id]
@@ -142300,6 +142503,7 @@ function fromRow(row) {
142300
142503
  packageSize: row.package_size == null ? null : Number(row.package_size),
142301
142504
  dataDigest: row.data_digest == null ? null : String(row.data_digest),
142302
142505
  dataSize: row.data_size == null ? null : Number(row.data_size),
142506
+ backupId: [...history].reverse().find((entry) => entry.backupId)?.backupId ?? null,
142303
142507
  status: String(row.status),
142304
142508
  history,
142305
142509
  error: row.error == null ? null : String(row.error),
@@ -142313,6 +142517,7 @@ function fromRow(row) {
142313
142517
  var import_node_crypto40 = __toESM(require("node:crypto"));
142314
142518
  var import_node_fs37 = __toESM(require("node:fs"));
142315
142519
  var import_node_path46 = __toESM(require("node:path"));
142520
+ var import_sql5 = __toESM(require("sql.js"));
142316
142521
  var AppSyncTarget = class {
142317
142522
  constructor(dataDir2, sessions, options2 = {}) {
142318
142523
  this.dataDir = dataDir2;
@@ -142320,7 +142525,7 @@ var AppSyncTarget = class {
142320
142525
  this.install = options2.install ?? installAppPackage;
142321
142526
  this.createBackup = options2.createBackup ?? createAppBackup;
142322
142527
  this.importData = options2.importData ?? importAppData;
142323
- this.restoreBackup = options2.restoreBackup ?? restoreAppBackup;
142528
+ this.restoreBackup = options2.restoreBackup ?? restoreAppBackupExact;
142324
142529
  this.rollbackVersion = options2.rollbackVersion ?? rollbackAppVersion;
142325
142530
  }
142326
142531
  commits = /* @__PURE__ */ new Map();
@@ -142345,7 +142550,15 @@ var AppSyncTarget = class {
142345
142550
  const session2 = this.sessions.getOwned(id, ownerId);
142346
142551
  if (!session2) return Promise.reject(new SyncSessionError("SYNC_SESSION_NOT_FOUND", "Synchronization session not found", 404));
142347
142552
  if (session2.status === "completed" && session2.outcome) {
142348
- return Promise.resolve({ session: session2, outcome: session2.outcome });
142553
+ const { backupId, ...outcome } = session2.outcome;
142554
+ return Promise.resolve({
142555
+ session: session2,
142556
+ outcome,
142557
+ backupId: typeof backupId === "string" ? backupId : null
142558
+ });
142559
+ }
142560
+ if (session2.status === "recovery-required") {
142561
+ return Promise.reject(new SyncSessionError("SYNC_RECOVERY_REQUIRED", "Synchronization requires operator recovery", 409));
142349
142562
  }
142350
142563
  const inFlight = this.commits.get(id);
142351
142564
  if (inFlight) return inFlight;
@@ -142375,14 +142588,11 @@ var AppSyncTarget = class {
142375
142588
  this.sessions.transition(id, ownerId, "committing");
142376
142589
  const pageDir = getPageDir(this.dataDir, ownerId, session2.appName);
142377
142590
  const previousMeta = readPageMeta(this.dataDir, ownerId, session2.appName);
142591
+ const previousDatabaseExisted = fsExists(import_node_path46.default.join(pageDir, "app.db"));
142378
142592
  let safetyBackupId;
142379
142593
  try {
142380
- if (session2.mode === "app-and-data" && previousMeta && fsExists(import_node_path46.default.join(pageDir, "app.db"))) {
142381
- const safety = await this.createBackup(pageDir, {
142382
- application: pageIdentity(previousMeta, ownerId, session2.appName),
142383
- source: "automatic",
142384
- reason: "peer-data-sync"
142385
- });
142594
+ if (session2.mode === "app-and-data" && previousMeta) {
142595
+ const safety = await this.createSafetyBackup(pageDir, previousMeta, ownerId, session2.appName, previousDatabaseExisted);
142386
142596
  safetyBackupId = safety.id;
142387
142597
  }
142388
142598
  const outcome = await this.install({ dataDir: this.dataDir, ownerId, packagePath, preserveTargetAccess: true });
@@ -142391,20 +142601,47 @@ var AppSyncTarget = class {
142391
142601
  if (!currentMeta) throw new AppDataError("APP_DATABASE_NOT_FOUND", "Application metadata disappeared during data synchronization");
142392
142602
  const versionChanged = !previousMeta || currentMeta.currentVersion !== previousMeta.currentVersion;
142393
142603
  try {
142394
- await this.importData({
142604
+ if (!previousMeta) {
142605
+ const safety = await this.createSafetyBackup(
142606
+ pageDir,
142607
+ currentMeta,
142608
+ ownerId,
142609
+ session2.appName,
142610
+ fsExists(import_node_path46.default.join(pageDir, "app.db"))
142611
+ );
142612
+ safetyBackupId = safety.id;
142613
+ }
142614
+ const imported = await this.importData({
142395
142615
  pageDir,
142396
142616
  application: pageIdentity(currentMeta, ownerId, session2.appName),
142397
142617
  archivePath: this.sessions.dataPath(id),
142398
- reason: "peer-data-sync"
142618
+ reason: "peer-data-sync",
142619
+ ...safetyBackupId ? { safetyBackupId } : {}
142399
142620
  });
142621
+ safetyBackupId ??= imported.safetyBackupId;
142400
142622
  } catch (dataError2) {
142401
- await this.rollbackAfterDataFailure({ pageDir, ownerId, appName: session2.appName, previousMeta, safetyBackupId, versionChanged });
142402
- throw dataError2;
142623
+ await this.rollbackAfterDataFailure({
142624
+ pageDir,
142625
+ ownerId,
142626
+ appName: session2.appName,
142627
+ previousMeta,
142628
+ currentMeta,
142629
+ safetyBackupId,
142630
+ versionChanged,
142631
+ previousDatabaseExisted
142632
+ });
142633
+ throw recoveredDataFailure(dataError2);
142403
142634
  }
142404
142635
  }
142405
- return { session: this.sessions.transition(id, ownerId, "completed", { outcome }), outcome };
142636
+ return {
142637
+ session: this.sessions.transition(id, ownerId, "completed", {
142638
+ outcome: { ...outcome, backupId: safetyBackupId ?? null }
142639
+ }),
142640
+ outcome,
142641
+ backupId: safetyBackupId ?? null
142642
+ };
142406
142643
  } catch (error5) {
142407
- this.sessions.transition(id, ownerId, error5 instanceof AppInstallError && error5.code === "APP_INSTALL_RECOVERY_REQUIRED" ? "recovery-required" : "failed", { error: publicInstallError(error5) });
142644
+ this.sessions.transition(id, ownerId, isRecoveryRequired(error5) ? "recovery-required" : "failed", { error: publicInstallError(error5) });
142408
142645
  throw error5;
142409
142646
  }
142410
142647
  }
@@ -142450,12 +142687,17 @@ var AppSyncTarget = class {
142450
142687
  async rollbackAfterDataFailure(input) {
142451
142688
  try {
142452
142689
  if (input.previousMeta && input.safetyBackupId) {
142453
- const currentMeta = readPageMeta(this.dataDir, input.ownerId, input.appName);
142690
+ if (input.versionChanged) await this.rollbackVersion({ dataDir: this.dataDir, ownerId: input.ownerId, name: input.appName });
142454
142691
  await this.restoreBackup(input.pageDir, input.safetyBackupId, {
142455
- application: pageIdentity(currentMeta ?? input.previousMeta, input.ownerId, input.appName)
142692
+ application: pageIdentity(input.previousMeta, input.ownerId, input.appName)
142456
142693
  });
142457
- if (input.versionChanged) await this.rollbackVersion({ dataDir: this.dataDir, ownerId: input.ownerId, name: input.appName });
142694
+ if (!input.previousDatabaseExisted) import_node_fs37.default.rmSync(import_node_path46.default.join(input.pageDir, "app.db"), { force: true });
142458
142695
  } else if (!input.previousMeta) {
142696
+ if (input.safetyBackupId) {
142697
+ await this.restoreBackup(input.pageDir, input.safetyBackupId, {
142698
+ application: pageIdentity(input.currentMeta, input.ownerId, input.appName)
142699
+ });
142700
+ }
142459
142701
  removeDirRecursive(input.pageDir);
142460
142702
  } else if (input.versionChanged) {
142461
142703
  await this.rollbackVersion({ dataDir: this.dataDir, ownerId: input.ownerId, name: input.appName });
@@ -142470,7 +142712,34 @@ var AppSyncTarget = class {
142470
142712
  );
142471
142713
  }
142472
142714
  }
142715
+ async createSafetyBackup(pageDir, previousMeta, ownerId, appName, databaseExisted) {
142716
+ const databasePath = import_node_path46.default.join(pageDir, "app.db");
142717
+ if (!databaseExisted) {
142718
+ const SQL = await (0, import_sql5.default)();
142719
+ const database = new SQL.Database();
142720
+ try {
142721
+ import_node_fs37.default.writeFileSync(databasePath, Buffer.from(database.export()), { mode: 384 });
142722
+ } finally {
142723
+ database.close();
142724
+ }
142725
+ }
142726
+ try {
142727
+ return await this.createBackup(pageDir, {
142728
+ application: pageIdentity(previousMeta, ownerId, appName),
142729
+ source: "automatic",
142730
+ reason: "peer-data-sync"
142731
+ });
142732
+ } finally {
142733
+ if (!databaseExisted) import_node_fs37.default.rmSync(databasePath, { force: true });
142734
+ }
142735
+ }
142473
142736
  };
142737
+ function recoveredDataFailure(error5) {
142738
+ return error5 instanceof AppDataError && error5.code === "APP_DATA_ROLLBACK_FAILED" ? new AppDataError("APP_DATA_IMPORT_FAILED", "Application data replacement failed; the target state was restored") : error5;
142739
+ }
142740
+ function isRecoveryRequired(error5) {
142741
+ return error5 instanceof AppInstallError && error5.code === "APP_INSTALL_RECOVERY_REQUIRED" || error5 instanceof AppDataError && error5.code === "APP_DATA_ROLLBACK_FAILED" || error5 instanceof SyncSessionError && error5.code === "SYNC_RECOVERY_REQUIRED";
142742
+ }
142474
142743
  function targetInstallStatus(error5) {
142475
142744
  if (error5 instanceof SyncSessionError) return error5.statusCode;
142476
142745
  if (error5 instanceof AppInstallError) return error5.code === "APP_MIGRATION_APPLY_FAILED" ? 422 : error5.statusCode;
@@ -142534,6 +142803,7 @@ var PEER_ERROR_CODES = /* @__PURE__ */ new Set([
142534
142803
  "SYNC_RECOVERY_REQUIRED",
142535
142804
  "SYNC_DATA_REQUIRED",
142536
142805
  "SYNC_DATA_NOT_EXPECTED",
142806
+ "SYNC_PROTOCOL_UNSUPPORTED",
142537
142807
  "SYNC_DATA_TOO_LARGE",
142538
142808
  "SYNC_DATA_SIZE_MISMATCH",
142539
142809
  "SYNC_DATA_DIGEST_MISMATCH",
@@ -142587,6 +142857,9 @@ var AppSyncSource = class {
142587
142857
  if (input.withData && !target.verifiedUserId) {
142588
142858
  throw new SyncSourceError(409, "Peer must be checked before application data can be synchronized", "PEER_NOT_VERIFIED");
142589
142859
  }
142860
+ if (input.withData && (target.protocolVersion ?? 0) < 2) {
142861
+ throw new SyncSourceError(409, "Peer protocol 2 or newer is required for application data synchronization", "PEER_PROTOCOL_UNSUPPORTED");
142862
+ }
142590
142863
  let dataDigest;
142591
142864
  let dataSize;
142592
142865
  if (input.withData) {
@@ -142605,6 +142878,7 @@ var AppSyncSource = class {
142605
142878
  signal: AbortSignal.timeout(3e4),
142606
142879
  body: JSON.stringify({
142607
142880
  id: syncId,
142881
+ protocolVersion: 2,
142608
142882
  mode: input.withData ? "app-and-data" : "app-only",
142609
142883
  appName: input.appName,
142610
142884
  appVersion: active.appVersion,
@@ -142738,12 +143012,20 @@ var AppSyncSource = class {
142738
143012
  signal: deadline.signal
142739
143013
  });
142740
143014
  if (response.ok) {
142741
- this.change(jobId, "completed");
143015
+ let backupId;
143016
+ try {
143017
+ backupId = await validatedCommitBackupId(response, job);
143018
+ } catch (error6) {
143019
+ const message = error6 instanceof Error ? error6.message : "Target commit response is invalid";
143020
+ this.change(jobId, "recovery-required", message);
143021
+ return;
143022
+ }
143023
+ this.change(jobId, "completed", void 0, backupId ?? void 0);
142742
143024
  return;
142743
143025
  }
142744
143026
  const error5 = await sourceResponseError(response);
142745
143027
  if (error5.code !== "SYNC_COMMIT_IN_PROGRESS") {
142746
- this.change(jobId, error5.code === "APP_INSTALL_RECOVERY_REQUIRED" ? "recovery-required" : "failed", error5.message);
143028
+ this.change(jobId, ["APP_INSTALL_RECOVERY_REQUIRED", "SYNC_RECOVERY_REQUIRED", "APP_DATA_ROLLBACK_FAILED"].includes(error5.code) ? "recovery-required" : "failed", error5.message);
142747
143029
  return;
142748
143030
  }
142749
143031
  lastError = error5;
@@ -142761,12 +143043,33 @@ var AppSyncSource = class {
142761
143043
  fail(id, error5) {
142762
143044
  return this.change(id, "failed", error5 instanceof SyncSourceError ? error5.message : "Synchronization failed");
142763
143045
  }
142764
- change(id, status, error5) {
142765
- const job = this.jobs.transition(id, status, error5);
143046
+ change(id, status, error5, backupId) {
143047
+ const job = this.jobs.transition(id, status, error5, backupId);
142766
143048
  this.events(id).emit("status", job);
142767
143049
  return job;
142768
143050
  }
142769
143051
  };
143052
+ async function validatedCommitBackupId(response, job) {
143053
+ const body = await response.json().catch(() => null);
143054
+ if (body?.success !== true || !isRecord11(body.data)) throw new Error("Target commit response is invalid");
143055
+ const session2 = body.data.session;
143056
+ const outcome = body.data.outcome;
143057
+ if (!isRecord11(session2) || session2.id !== job.syncId || session2.status !== "completed" || session2.appName !== job.appName || session2.appVersion !== job.appVersion || session2.packageDigest !== job.packageDigest || !isRecord11(outcome) || outcome.name !== job.appName || outcome.appVersion !== job.appVersion || outcome.digest !== job.packageDigest) {
143058
+ throw new Error("Target commit response does not match the synchronization job");
143059
+ }
143060
+ const backupId = body.data.backupId;
143061
+ if (job.withData) {
143062
+ if (typeof backupId !== "string" || !isAppBackupId(backupId)) {
143063
+ throw new Error("Target data synchronization did not return a valid safety backup ID");
143064
+ }
143065
+ return backupId;
143066
+ }
143067
+ if (backupId !== null) throw new Error("Target application-only synchronization returned an unexpected backup ID");
143068
+ return null;
143069
+ }
143070
+ function isRecord11(value) {
143071
+ return typeof value === "object" && value !== null && !Array.isArray(value);
143072
+ }
142770
143073
  async function activePackage(dataDir2, ownerId, appName) {
142771
143074
  const meta = readPageMeta(dataDir2, ownerId, appName);
142772
143075
  if (!meta) throw new SyncSourceError(404, "Application not found", "APP_NOT_FOUND");
@@ -142857,6 +143160,9 @@ async function syncTargetRoutes(app, target) {
142857
143160
  const nameError = validateName(appName);
142858
143161
  if (nameError) throw new SyncSessionError("APP_NAME_INVALID", nameError, 400);
142859
143162
  const mode = body?.mode === "app-only" || body?.mode === "app-and-data" ? body.mode : invalidMode();
143163
+ if (body?.protocolVersion !== 2) {
143164
+ throw new SyncSessionError("SYNC_PROTOCOL_UNSUPPORTED", "Peer synchronization protocol 2 is required", 409);
143165
+ }
142860
143166
  const session2 = target.create({
142861
143167
  id: requiredString3(body?.id, "id"),
142862
143168
  ownerId,
@@ -142914,7 +143220,7 @@ async function syncTargetRoutes(app, target) {
142914
143220
  if (!ownerId) return;
142915
143221
  try {
142916
143222
  const result = await target.commit(request.params.id, ownerId);
142917
- return { success: true, data: { session: publicSession(result.session), outcome: result.outcome } };
143223
+ return { success: true, data: { session: publicSession(result.session), outcome: result.outcome, backupId: result.backupId } };
142918
143224
  } catch (error5) {
142919
143225
  return targetError(reply, error5);
142920
143226
  }
@@ -143210,7 +143516,7 @@ function updateContext(context, body) {
143210
143516
  if ("user" in body) {
143211
143517
  if (body.user === null) {
143212
143518
  next.user = null;
143213
- } else if (isRecord11(body.user) && typeof body.user.id === "string" && body.user.id.trim()) {
143519
+ } else if (isRecord12(body.user) && typeof body.user.id === "string" && body.user.id.trim()) {
143214
143520
  const user = findUserById(body.user.id);
143215
143521
  if (!user) return { ok: false, error: "Dev context user must be a Server user" };
143216
143522
  next.user = userToContextUser(user, next.pageOwnerId);
@@ -143305,7 +143611,7 @@ function toBasicUser(user) {
143305
143611
  role: user.role
143306
143612
  };
143307
143613
  }
143308
- function isRecord11(value) {
143614
+ function isRecord12(value) {
143309
143615
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
143310
143616
  }
143311
143617