better-supabase 0.33.0 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/dist/ai-sdk/agents/index.d.ts +2 -2
  2. package/dist/{app-tables-IrglDJCs.d.ts → app-tables-Don-aNOB.d.ts} +1 -1
  3. package/dist/{authorization-BlmDNI2b.d.ts → authorization-DpVtxuKM.d.ts} +16 -1
  4. package/dist/{bind-DP-KLgYI.d.ts → bind-BA05aoY9.d.ts} +1 -1
  5. package/dist/{block-env-CJ38ZSTP.d.ts → block-env-UX42PHLP.d.ts} +3 -3
  6. package/dist/{block-tables-CQTU71zn.d.ts → block-tables-Bre1zjau.d.ts} +1 -1
  7. package/dist/blocks/ai-chat/index.d.ts +3 -3
  8. package/dist/blocks/announcements/index.d.ts +3 -3
  9. package/dist/blocks/api-keys/index.d.ts +1 -1
  10. package/dist/blocks/attachments/index.d.ts +1 -1
  11. package/dist/blocks/audit/index.d.ts +2 -2
  12. package/dist/blocks/automations/index.d.ts +1 -1
  13. package/dist/blocks/billing/index.d.ts +1 -1
  14. package/dist/blocks/bookings/index.d.ts +1 -1
  15. package/dist/blocks/calendar/index.d.ts +1 -1
  16. package/dist/blocks/comments/index.d.ts +4 -4
  17. package/dist/blocks/drive/index.js +1 -1
  18. package/dist/blocks/entitlements/index.d.ts +2 -2
  19. package/dist/blocks/forms/index.d.ts +1 -1
  20. package/dist/blocks/inbox/index.d.ts +4 -4
  21. package/dist/blocks/index.d.ts +1 -1
  22. package/dist/blocks/messaging/index.d.ts +4 -4
  23. package/dist/blocks/mfa/index.d.ts +1 -1
  24. package/dist/blocks/notifications/index.d.ts +3 -3
  25. package/dist/blocks/onboarding/index.d.ts +1 -1
  26. package/dist/blocks/organizations/index.d.ts +2 -2
  27. package/dist/blocks/permissions/index.d.ts +1 -1
  28. package/dist/blocks/push/index.d.ts +1 -1
  29. package/dist/blocks/reactions/index.d.ts +3 -3
  30. package/dist/blocks/saved-views/index.d.ts +1 -1
  31. package/dist/blocks/search/index.d.ts +2 -2
  32. package/dist/blocks/sessions/index.d.ts +1 -1
  33. package/dist/blocks/settings/index.d.ts +1 -1
  34. package/dist/blocks/subjects/index.d.ts +1 -1
  35. package/dist/blocks/tags/index.d.ts +1 -1
  36. package/dist/blocks/undo/index.d.ts +1 -1
  37. package/dist/blocks/usage/index.d.ts +1 -1
  38. package/dist/blocks/workflow-editor/index.d.ts +3 -3
  39. package/dist/blocks/workflows/index.d.ts +3 -3
  40. package/dist/claims/index.d.ts +3 -3
  41. package/dist/cli/add-C13ZqJ_N.js +1 -0
  42. package/dist/cli/{add-BDLLVLI8.js → add-DoEtJhZG.js} +2 -2
  43. package/dist/cli/{add-D2pKTbPw.js → add-THXE7juv.js} +9 -9
  44. package/dist/cli/{app-table-files-CimWi_eh.js → app-table-files-BqLd5TuX.js} +2 -2
  45. package/dist/cli/{backfill-B1xAsdL4.js → backfill-D-2W0fNT.js} +1 -1
  46. package/dist/cli/bin.js +1 -1
  47. package/dist/cli/{blocks-rBeis04I.js → blocks-BVU_FoLo.js} +1 -1
  48. package/dist/cli/{blocks-DtZtn-R4.js → blocks-XwUHeyUH.js} +1 -1
  49. package/dist/cli/{cache-CvBRwv02.js → cache-D4nwCBXc.js} +1 -1
  50. package/dist/cli/{codemod-DYbVbJ-e.js → codemod-Dh4lf_k4.js} +1 -1
  51. package/dist/cli/{content-mapper-DrhtDsAm.js → content-mapper-CwFH_PEn.js} +2 -2
  52. package/dist/cli/{doctor-Dn4TzGmw.js → doctor-CyAMbZ_s.js} +14 -14
  53. package/dist/cli/{gen-BbeS0KgF.js → gen-EAUNnUY7.js} +11 -11
  54. package/dist/cli/index.d.ts +1 -1
  55. package/dist/cli/index.js +6 -6
  56. package/dist/cli/{init-C30xdMSs.js → init-BRmmmGHJ.js} +8 -8
  57. package/dist/cli/{live-Ctc8Qh9Y.js → live-CV9mn-xC.js} +2 -2
  58. package/dist/cli/{mcp-5J0kUOtD.js → mcp-CnaxcLWa.js} +2 -2
  59. package/dist/cli/{metadata-DxhUNctA.js → metadata-CFQGBR5E.js} +3 -3
  60. package/dist/cli/{migrate-ockrh3UX.js → migrate-z5oHDGNs.js} +1 -1
  61. package/dist/cli/{migration-safety-CLrqC0D-.js → migration-safety-BtAPMEZa.js} +1 -1
  62. package/dist/cli/{migrations-CZTg2UJM.js → migrations-CNa62JSi.js} +2 -2
  63. package/dist/cli/{module-migration-BptQzmj2.js → module-migration-CKJ8kRm1.js} +2 -2
  64. package/dist/cli/{powersync-DIvsipKr.js → powersync-BgoAWeRT.js} +3 -3
  65. package/dist/cli/powersync-DoCruiOt.js +1 -0
  66. package/dist/cli/{print-DdHt8xCc.js → print-CoqKHoy0.js} +2 -2
  67. package/dist/cli/{providers-k-1cEna6.js → providers-CfbFxUOQ.js} +1 -1
  68. package/dist/cli/{prune-workflows-Ddv-GfkO.js → prune-workflows-BigCoXLw.js} +1 -1
  69. package/dist/cli/{remove-DEEQDoc7.js → remove-C9zwn-Kk.js} +5 -5
  70. package/dist/cli/{render-SjSVz8yK.js → render-DQCU_kBW.js} +3 -3
  71. package/dist/cli/{run-Ixt9mEb6.js → run-CVaBuT18.js} +25 -25
  72. package/dist/cli/{run-DdhIK7-K.js → run-DOD00FFl.js} +8 -8
  73. package/dist/cli/{shared-p6sxli_5.js → shared-COtj7l3r.js} +1 -1
  74. package/dist/cli/{snapshot-Dd_8B9g-.js → snapshot-BvlEmTB0.js} +2 -2
  75. package/dist/cli/{source-BYvVe_Es.js → source-BhZRCitG.js} +1 -1
  76. package/dist/cli/{spec-liRzcZTa.js → spec-Bo2wIViH.js} +1 -1
  77. package/dist/cli/{spec-BxQgllJY.js → spec-DsMWuJLv.js} +2 -2
  78. package/dist/cli/{sql-layout-DHwiUOaD.js → sql-layout-CA7xgRjR.js} +2 -2
  79. package/dist/cli/{sync-CreQWj53.js → sync-D9xSGdzO.js} +4 -4
  80. package/dist/cli/{upgrade-U7IKj45h.js → upgrade-XK_CQKVJ.js} +2 -2
  81. package/dist/cli/{upgrade-3NQOUO1_.js → upgrade-Ykf0LLEB.js} +5 -5
  82. package/dist/cli/{version-mBwP-aMG.js → version-Dfdz7KSh.js} +1 -1
  83. package/dist/client/index.d.ts +5 -5
  84. package/dist/client/native/index.d.ts +4 -4
  85. package/dist/config/index.d.ts +2 -2
  86. package/dist/{context-D7jICqdN.d.ts → context-BGC0J3t9.d.ts} +1 -1
  87. package/dist/contract/index.d.ts +3 -3
  88. package/dist/{controller-DxtxeYdf.d.ts → controller-CQrkLoRX.d.ts} +1 -1
  89. package/dist/create/index.d.ts +3 -3
  90. package/dist/create/index.js +1 -1
  91. package/dist/create/lite/index.d.ts +3 -3
  92. package/dist/create/lite/index.js +1 -1
  93. package/dist/{entitlements-w04ivvAy.d.ts → entitlements-BOWTZaRf.d.ts} +1 -1
  94. package/dist/{field-errors-DKCaSlZw.d.ts → field-errors-DxPZYw2m.d.ts} +4 -4
  95. package/dist/{index-CbUXFzQV.d.ts → index-BfU0KR0X.d.ts} +1 -1
  96. package/dist/{index-BgkHbf9C.d.ts → index-Bhkag9ZE.d.ts} +6 -6
  97. package/dist/{index-BZCmy767.d.ts → index-Bz0WLuh_.d.ts} +2 -2
  98. package/dist/{index-DU0UwWvL.d.ts → index-CJB50jzQ.d.ts} +2 -2
  99. package/dist/{index-BdC2IqkU.d.ts → index-CeUwyJ3Z.d.ts} +2 -2
  100. package/dist/{index-CiE37wKX.d.ts → index-DNAkWDXc.d.ts} +1 -1
  101. package/dist/{index-BvcMQYL-.d.ts → index-QTZIopQj.d.ts} +1 -1
  102. package/dist/mapper/bin.js +5 -5
  103. package/dist/mcp/index.d.ts +1 -1
  104. package/dist/next/index.d.ts +4 -4
  105. package/dist/{operations-CsCwruKT.d.ts → operations-BG6prEnh.d.ts} +1 -1
  106. package/dist/{options-B56njigZ.js → options-CjocPkX1.js} +2 -0
  107. package/dist/otel/index.js +4 -4
  108. package/dist/{permissions-BP593xxk.d.ts → permissions-CoHsUtZS.d.ts} +1 -1
  109. package/dist/{ports-BVLhLUvR.d.ts → ports-XvgCe7ey.d.ts} +1 -1
  110. package/dist/powersync/index.d.ts +2 -2
  111. package/dist/preset/index.d.ts +3 -3
  112. package/dist/{project-D4ArwcS5.js → project-B7nqCzn5.js} +1 -1
  113. package/dist/{push-token-B0j171on.d.ts → push-token-kcc04ZaS.d.ts} +1 -1
  114. package/dist/react/index.d.ts +5 -5
  115. package/dist/react/native/index.d.ts +1 -1
  116. package/dist/react/server.d.ts +5 -5
  117. package/dist/realtime/index.d.ts +3 -3
  118. package/dist/records/index.d.ts +3 -3
  119. package/dist/server/index.d.ts +3 -3
  120. package/dist/solid/index.d.ts +5 -5
  121. package/dist/sql/index.d.ts +5 -5
  122. package/dist/sql/index.js +1 -1
  123. package/dist/{sql-DiUP7fKX.js → sql-DdtukoIm.js} +243 -110
  124. package/dist/ssr/index.d.ts +1 -1
  125. package/dist/svelte/index.d.ts +5 -5
  126. package/dist/{tenant-B3IIq8Eq.d.ts → tenant-DkKbvK5T.d.ts} +1 -1
  127. package/dist/testing/index.d.ts +3 -3
  128. package/dist/{topic-D2MyBeaI.d.ts → topic-B6zuexk7.d.ts} +1 -1
  129. package/dist/{types-BFEKRmEK.d.ts → types-BvHw2cCS.d.ts} +2 -2
  130. package/dist/vue/index.d.ts +5 -5
  131. package/dist/{watch-topic-q6krNw0T.d.ts → watch-topic-YYSVJGDY.d.ts} +1 -1
  132. package/dist/yjs/index.d.ts +1 -1
  133. package/package.json +1 -1
  134. package/schemas/config-v1.json +5 -0
  135. package/dist/cli/add-BaOCKKt6.js +0 -1
  136. package/dist/cli/powersync-CmsXOuui.js +0 -1
@@ -50,7 +50,7 @@ import { n as WORK_ORDER_STATUSES, r as dispatchSqlOptions, t as WORK_ORDER_PRIO
50
50
  import { t as documentsSqlOptions } from "./options-C4kpi6HE.js";
51
51
  import { t as domainsSqlOptions } from "./options-eLIedotm.js";
52
52
  import { t as donationsSqlOptions } from "./options-ompJjxkV.js";
53
- import { t as driveSqlOptions } from "./options-B56njigZ.js";
53
+ import { t as driveSqlOptions } from "./options-CjocPkX1.js";
54
54
  import { t as employeesSqlOptions } from "./options-XiD_Y3oK.js";
55
55
  import { t as enrollmentsSqlOptions } from "./options-eIEk0vqV.js";
56
56
  import { t as expensesSqlOptions } from "./options-CuPWezcV.js";
@@ -8376,6 +8376,69 @@ function rankSql(type) {
8376
8376
  pattern: RANK_KEY_PATTERN
8377
8377
  };
8378
8378
  }
8379
+ // src/sql/provider-rows.ts
8380
+ const RESOURCE = /^[a-z_][a-z0-9_]{0,62}$/;
8381
+ const isResourceName = (rows) => typeof rows === "string" && RESOURCE.test(rows);
8382
+ function providerRowCheck(ctx, where, rows, key) {
8383
+ const rowsWith = ctx.providerRowsWith;
8384
+ if (rowsWith === void 0) throw new TypeError(`${where}.rows needs blocks.permissions.model "provider" and an authorization provider with functions.rowsWith`);
8385
+ const forUser = ctx.providerRowsWithFor;
8386
+ const permission = sqlString(key);
8387
+ return (id, user) => {
8388
+ const ids = `array[${id}::text]`;
8389
+ const member = (set) => `${id}::text in (select r.id::text from ${set} as r(id))`;
8390
+ const own = member(fillTemplate("authorization.functions.rowsWith", rowsWith, {
8391
+ resource: rows,
8392
+ permission,
8393
+ ids
8394
+ }));
8395
+ if (forUser === void 0) return `(${user} = auth.uid() and ${own})`;
8396
+ return `(case when ${user} = auth.uid() then ${own} when ${user} is not null then ${member(fillTemplate("authorization.functions.rowsWithFor", forUser, {
8397
+ user,
8398
+ resource: rows,
8399
+ permission,
8400
+ ids
8401
+ }))} else false end)`;
8402
+ };
8403
+ }
8404
+ // src/sql/modules/drive-roles.ts
8405
+ const QUALIFIED$2 = /^[A-Za-z_][\w$]*\.[A-Za-z_][\w$]*$/;
8406
+ function providerRoles(ctx, all, at, rows, map) {
8407
+ if (!isResourceName(rows) || !isRecord$1(map) || Object.keys(map).length === 0 || !Object.entries(map).every(([role, key]) => all.includes(role) && typeof key === "string" && key !== "")) throw new TypeError(`${at} takes { rows, roles }: the provider's resource name and a permission key for each of options.roles it grants`);
8408
+ const checks = all.filter((role) => map[role] !== void 0).toReversed().map((role) => ({
8409
+ role,
8410
+ check: providerRowCheck(ctx, at, rows, String(map[role]))
8411
+ }));
8412
+ return {
8413
+ label: `the authorization provider's grants on ${rows}`,
8414
+ role: (id, user) => `case ${checks.map(({ role, check }) => `when ${check(id, user)} then ${sqlString(role)}`).join(" ")} end`
8415
+ };
8416
+ }
8417
+ /** `options.roleFunctions`: app functions that return the caller's role. */
8418
+ function driveRoleFunctions(ctx, all) {
8419
+ const where = "blocks.drive.options.roleFunctions";
8420
+ const raw = ctx.option("roleFunctions");
8421
+ if (raw === void 0) return {
8422
+ node: void 0,
8423
+ drive: void 0
8424
+ };
8425
+ if (!isRecord$1(raw)) throw new TypeError(`${where} takes { node, drive } function names or { rows, roles }`);
8426
+ const parse = (key) => {
8427
+ const value = raw[key];
8428
+ if (value === void 0) return;
8429
+ if (isRecord$1(value)) return providerRoles(ctx, all, `${where}.${key}`, value["rows"], value["roles"]);
8430
+ if (typeof value !== "string" || !QUALIFIED$2.test(value)) throw new TypeError(`${where}.${key} must be a schema-qualified function name, such as public.file_node_role, or { rows, roles }`);
8431
+ const fn = value.split(".").map(sqlIdent).join(".");
8432
+ return {
8433
+ label: fn,
8434
+ role: (id, user) => `${fn}(${id}, ${user})`
8435
+ };
8436
+ };
8437
+ return {
8438
+ node: parse("node"),
8439
+ drive: parse("drive")
8440
+ };
8441
+ }
8379
8442
  // src/sql/subject-write.ts
8380
8443
  /**
8381
8444
  * Whether the caller holds the `write` key a registered subject type names
@@ -9122,6 +9185,8 @@ const NAMES$113 = {
9122
9185
  "drives",
9123
9186
  "driveKinds",
9124
9187
  "sources",
9188
+ "roleFunctions",
9189
+ "readPolicy",
9125
9190
  "extraColumns"
9126
9191
  ],
9127
9192
  tables: {
@@ -9225,7 +9290,7 @@ const NAMES$113 = {
9225
9290
  },
9226
9291
  driveGrants: {
9227
9292
  name: "drive_drive_grants",
9228
- app: {},
9293
+ app: { unused: (ctx) => ctx.has("driveGrants", "principalType") ? ["user", "team"] : ["principalType", "principalId"] },
9229
9294
  optionalTable: true,
9230
9295
  lifecycle: {
9231
9296
  tenant: "tenant",
@@ -9237,12 +9302,21 @@ const NAMES$113 = {
9237
9302
  drive: "drive_id",
9238
9303
  principalType: "principal_type",
9239
9304
  principalId: "principal_id",
9305
+ user: "user_id",
9306
+ team: "team_id",
9240
9307
  role: "role",
9241
9308
  expiresAt: "expires_at",
9242
9309
  createdBy: "created_by",
9243
9310
  createdAt: "created_at"
9244
9311
  },
9245
- optional: ["expiresAt", "createdBy"]
9312
+ optional: [
9313
+ "principalType",
9314
+ "principalId",
9315
+ "user",
9316
+ "team",
9317
+ "expiresAt",
9318
+ "createdBy"
9319
+ ]
9246
9320
  },
9247
9321
  connections: {
9248
9322
  name: "drive_connections",
@@ -9373,12 +9447,20 @@ function driveKit(ctx, own) {
9373
9447
  const teamColumn = !typed && ctx.has("grants", "team");
9374
9448
  const expiring = ctx.has("grants", "expiresAt");
9375
9449
  const drives = ctx.flag("drives", false);
9376
- const driveColumn = has("drive");
9450
+ const driveColumn = has("drive") && (!ctx.owns("nodes") || drives);
9377
9451
  const sourceColumn = has("source");
9378
9452
  const externalColumn = has("externalId");
9379
9453
  const metadataColumn = has("externalMetadata");
9380
9454
  const holdColumn = has("legalHoldUntil");
9381
9455
  if (drives && !driveColumn) throw new TypeError("blocks.drive.options.drives needs blocks.drive.columns.nodes.drive");
9456
+ const driveTyped = drives && ctx.has("driveGrants", "principalType") && ctx.has("driveGrants", "principalId");
9457
+ const driveUserColumn = drives && ctx.has("driveGrants", "user");
9458
+ const driveTeamColumn = !driveTyped && driveUserColumn && ctx.has("driveGrants", "team");
9459
+ if (drives && !driveTyped && !driveUserColumn) throw new TypeError("blocks.drive.columns.driveGrants needs principalType and principalId, or user (and team)");
9460
+ const drivePrincipalTypes = driveTyped ? "('user', 'team', 'role')" : driveTeamColumn ? "('user', 'team')" : "('user')";
9461
+ const roleFunctions = driveRoleFunctions(ctx, driveRoles(ctx).all);
9462
+ if (roleFunctions.drive !== void 0 && !drives) throw new TypeError("blocks.drive.options.roleFunctions.drive needs blocks.drive.options.drives");
9463
+ const readPolicy = ctx.flag("readPolicy", true);
9382
9464
  if (externalColumn && !sourceColumn) throw new TypeError("blocks.drive.columns.nodes.externalId needs blocks.drive.columns.nodes.source");
9383
9465
  if (drives && (!ctx.hasTable("drives") || !ctx.hasTable("driveGrants") || !ctx.hasTable("connections") || !ctx.has("drives", "kind") || !ctx.has("drives", "owner") || !ctx.has("drives", "connection"))) throw new TypeError("blocks.drive.options.drives needs the drives, driveGrants and connections tables with kind, owner and connection columns");
9384
9466
  const driveKinds = ctx.list("driveKinds", ["shared"]);
@@ -9471,27 +9553,35 @@ function driveKit(ctx, own) {
9471
9553
  targetLabel: `${row}.${c("name")}`,
9472
9554
  summary: sqlString(summary)
9473
9555
  });
9556
+ const teamMember = (team, uid) => teams === void 0 ? "false" : `exists (select 1 from ${teams.table("members")} tm where tm.${teams.col("members", "team")}::text = ${team}::text and tm.${teams.col("members", "user")} = ${uid})`;
9474
9557
  const principalMatch = (grant, uid, tenantId) => {
9475
- const teamMember = (team) => teams === void 0 ? "false" : `exists (select 1 from ${teams.table("members")} tm where tm.${teams.col("members", "team")}::text = ${team}::text and tm.${teams.col("members", "user")} = ${uid})`;
9476
- if (!typed) return `(${grant}.${g("user")} = ${uid}${teamColumn ? ` or (${grant}.${g("team")} is not null and ${teamMember(`${grant}.${g("team")}`)})` : ""})`;
9558
+ if (!typed) return `(${grant}.${g("user")} = ${uid}${teamColumn ? ` or (${grant}.${g("team")} is not null and ${teamMember(`${grant}.${g("team")}`, uid)})` : ""})`;
9477
9559
  return `((${grant}.${g("principalType")} = 'user' and ${grant}.${g("principalId")} = ${uid}::text)
9478
- or (${grant}.${g("principalType")} = 'team' and ${teamMember(`${grant}.${g("principalId")}`)})
9560
+ or (${grant}.${g("principalType")} = 'team' and ${teamMember(`${grant}.${g("principalId")}`, uid)})
9479
9561
  or (${grant}.${g("principalType")} = 'role' and exists (select 1 from ${tenant.table("memberships")} mr where mr.${m("tenant")} = ${tenantId} and mr.${m("user")} = ${uid} and mr.${m("role")}::text = ${grant}.${g("principalId")}${activeMembership(ctx, "mr")})))`;
9480
9562
  };
9563
+ const drivePrincipalMatch = (grant, uid, tenantId) => {
9564
+ if (!driveTyped) return `(${grant}.${dg("user")} = ${uid}${driveTeamColumn ? ` or (${grant}.${dg("team")} is not null and ${teamMember(`${grant}.${dg("team")}`, uid)})` : ""})`;
9565
+ return `((${grant}.${dg("principalType")} = 'user' and ${grant}.${dg("principalId")} = ${uid}::text)
9566
+ or (${grant}.${dg("principalType")} = 'team' and ${teamMember(`${grant}.${dg("principalId")}`, uid)})
9567
+ or (${grant}.${dg("principalType")} = 'role' and exists (select 1 from ${tenant.table("memberships")} mr where mr.${m("tenant")} = ${tenantId} and mr.${m("user")} = ${uid} and mr.${m("role")}::text = ${grant}.${dg("principalId")}${activeMembership(ctx, "mr")})))`;
9568
+ };
9569
+ const drivePrincipalType = (grant) => driveTyped ? `${grant}.${dg("principalType")}` : driveTeamColumn ? `case when ${grant}.${dg("user")} is not null then 'user' else 'team' end` : "'user'";
9570
+ const drivePrincipalId = (grant) => driveTyped ? `${grant}.${dg("principalId")}` : driveTeamColumn ? `coalesce(${grant}.${dg("user")}::text, ${grant}.${dg("team")}::text)` : `${grant}.${dg("user")}::text`;
9481
9571
  const grantLive = (grant) => expiring ? ` and (${grant}.${g("expiresAt")} is null or ${grant}.${g("expiresAt")} > now())` : "";
9482
9572
  const driveExpiring = drives && ctx.has("driveGrants", "expiresAt");
9483
9573
  const driveGrantLive = (grant) => driveExpiring ? ` and (${grant}.${dg("expiresAt")} is null or ${grant}.${dg("expiresAt")} > now())` : "";
9484
9574
  const principalType = (grant) => typed ? `${grant}.${g("principalType")}` : teamColumn ? `case when ${grant}.${g("user")} is not null then 'user' else 'team' end` : "'user'";
9485
9575
  const principalId = (grant) => typed ? `${grant}.${g("principalId")}` : teamColumn ? `coalesce(${grant}.${g("user")}::text, ${grant}.${g("team")}::text)` : `${grant}.${g("user")}::text`;
9486
9576
  const fileJson = A === void 0 ? "" : `, 'attachmentId', ($1).${n("attachment")}, 'file', (select jsonb_build_object('mimeType', fa.${a("mimeType")}, 'size', fa.${a("size")}, 'status', fa.${a("status")}, 'uploadedAt', fa.${a("uploadedAt")}) from ${A} fa where fa.${a("id")} = ($1).${n("attachment")})`;
9487
- const nodeJson = (file) => `jsonb_build_object('id', ($1).${n("id")}, 'organizationId', ($1).${n("tenant")}, 'driveId', ${drives ? `($1).${n("drive")}` : "null"}, 'parentId', ($1).${n("parent")}, 'kind', ($1).${n("kind")}, 'name', ($1).${n("name")}, 'rank', ${ranked ? `($1).${n("rank")}` : "null"}, 'source', ${sourceColumn ? `($1).${n("source")}` : "null"}, 'externalId', ${externalColumn ? `($1).${n("externalId")}` : "null"}, 'externalMetadata', ${metadataColumn ? `($1).${n("externalMetadata")}` : "null"}, 'legalHoldUntil', ${holdColumn ? `($1).${n("legalHoldUntil")}` : "null"}, 'createdBy', ${has("createdBy") ? `($1).${n("createdBy")}` : "null"}, 'createdAt', ($1).${n("createdAt")}, 'updatedAt', ${has("updatedAt") ? `($1).${n("updatedAt")}` : "null"}, 'deletedAt', ${binColumn ? `($1).${n("deletedAt")}` : "null"}${file}${extras.length === 0 ? "" : `, 'fields', ${columnsObject("($1)", extras.map((column) => column.name))}`})`;
9577
+ const nodeJson = (file) => `jsonb_build_object('id', ($1).${n("id")}, 'organizationId', ($1).${n("tenant")}, 'driveId', ${driveColumn ? `($1).${n("drive")}` : "null"}, 'parentId', ($1).${n("parent")}, 'kind', ($1).${n("kind")}, 'name', ($1).${n("name")}, 'rank', ${ranked ? `($1).${n("rank")}` : "null"}, 'source', ${sourceColumn ? `($1).${n("source")}` : "null"}, 'externalId', ${externalColumn ? `($1).${n("externalId")}` : "null"}, 'externalMetadata', ${metadataColumn ? `($1).${n("externalMetadata")}` : "null"}, 'legalHoldUntil', ${holdColumn ? `($1).${n("legalHoldUntil")}` : "null"}, 'createdBy', ${has("createdBy") ? `($1).${n("createdBy")}` : "null"}, 'createdAt', ($1).${n("createdAt")}, 'updatedAt', ${has("updatedAt") ? `($1).${n("updatedAt")}` : "null"}, 'deletedAt', ${binColumn ? `($1).${n("deletedAt")}` : "null"}${file}${extras.length === 0 ? "" : `, 'fields', ${columnsObject("($1)", extras.map((column) => column.name))}`})`;
9488
9578
  const json = (row) => `${fn("drive_node_json")}(${row})`;
9489
9579
  const withRole = (row) => `(${json(row)} || jsonb_build_object('role', ${fn("drive_role")}((${row}).${n("id")}), 'readOnly', ${readOnly(`(${row})`)}, 'held', ${fn("drive_node_held")}((${row}).${n("id")})))`;
9490
9580
  const orderBy = (alias) => `(${alias}.${n("kind")} = 'folder') desc${ranked ? `, ${alias}.${n("rank")}` : ""}, lower(${alias}.${n("name")}), ${alias}.${n("id")}`;
9491
9581
  const touch = has("updatedAt") ? `, ${n("updatedAt")} = now()` : "";
9492
9582
  const insertColumns = [
9493
9583
  n("tenant"),
9494
- ...drives ? [n("drive")] : [],
9584
+ ...driveColumn ? [n("drive")] : [],
9495
9585
  n("parent"),
9496
9586
  n("kind"),
9497
9587
  n("name"),
@@ -9502,7 +9592,7 @@ function driveKit(ctx, own) {
9502
9592
  ];
9503
9593
  const insertValues = [
9504
9594
  "drive_insert_node.tenant",
9505
- ...drives ? [`coalesce(drive_insert_node.drive, v_parent.${n("drive")})`] : [],
9595
+ ...driveColumn ? ["v_drive"] : [],
9506
9596
  "drive_insert_node.parent",
9507
9597
  "drive_insert_node.kind",
9508
9598
  "v_name",
@@ -9517,8 +9607,8 @@ function driveKit(ctx, own) {
9517
9607
  insert into ${G} (${g("tenant")}, ${g("node")}, ${g("user")}, ${g("role")})
9518
9608
  values (${node}.${n("tenant")}, ${node}.${n("id")}, ${uid}, ${role});`;
9519
9609
  const siblings = (alias, tenantId, parent, drive) => {
9520
- if (drives && drive === void 0) throw new Error("a drive-wide name check needs the drive");
9521
- return `${alias}.${n("tenant")} = ${tenantId} and ${alias}.${n("parent")} is not distinct from ${parent}${drives ? ` and ${alias}.${n("drive")} = ${drive}` : ""}${live(alias)}`;
9610
+ if (driveColumn && drive === void 0) throw new Error("a drive-wide name check needs the drive");
9611
+ return `${alias}.${n("tenant")} = ${tenantId} and ${alias}.${n("parent")} is not distinct from ${parent}${driveColumn ? ` and ${alias}.${n("drive")} = ${drive}` : ""}${live(alias)}`;
9522
9612
  };
9523
9613
  return {
9524
9614
  ctx,
@@ -9555,6 +9645,16 @@ function driveKit(ctx, own) {
9555
9645
  dg,
9556
9646
  c,
9557
9647
  driveColumn,
9648
+ driveTyped,
9649
+ driveTeamColumn,
9650
+ driveUserColumn,
9651
+ drivePrincipalTypes,
9652
+ drivePrincipalMatch,
9653
+ drivePrincipalType,
9654
+ drivePrincipalId,
9655
+ nodeRole: roleFunctions.node,
9656
+ driveRole: roleFunctions.drive,
9657
+ readPolicy,
9558
9658
  sourceColumn,
9559
9659
  externalColumn,
9560
9660
  metadataColumn,
@@ -30069,35 +30169,19 @@ const BULK = {
30069
30169
  };
30070
30170
  // src/sql/modules/calendar-features.ts
30071
30171
  const QUALIFIED$1 = /^[A-Za-z_][\w$]*\.[A-Za-z_][\w$]*$/;
30072
- const RESOURCE = /^[a-z_][a-z0-9_]{0,62}$/;
30073
30172
  /**
30074
30173
  * `accessFunctions.read` or `write`: an app function `(calendar_id, user_id)`,
30075
30174
  * or `{ rows, key }`, the authorization provider's per-row grants of `key` on
30076
- * resource `rows`, through `rowsWithFor` (or `rowsWith` for the caller only).
30175
+ * resource `rows`, through `rowsWith` for the caller and `rowsWithFor` for
30176
+ * anyone else.
30077
30177
  */
30078
30178
  function appFunction(ctx, value, key) {
30079
30179
  const where = `blocks.calendar.options.accessFunctions.${key}`;
30080
30180
  if (value === void 0) return;
30081
30181
  if (isRecord$1(value)) {
30082
30182
  const { rows, key: permission } = value;
30083
- if (typeof rows !== "string" || !RESOURCE.test(rows) || typeof permission !== "string" || permission === "") throw new TypeError(`${where} takes { rows, key }: the provider's resource name and the permission key`);
30084
- if (ctx.providerRowsWith === void 0) throw new TypeError(`${where}.rows needs blocks.permissions.model "provider" and an authorization provider with functions.rowsWith`);
30085
- const forUser = ctx.providerRowsWithFor;
30086
- const rowsWith = ctx.providerRowsWith;
30087
- return (calendar, user) => {
30088
- const ids = `array[${calendar}::text]`;
30089
- const member = `${calendar}::text in (select r.id::text from ${forUser === void 0 ? fillTemplate(`authorization.functions.rowsWith`, rowsWith, {
30090
- resource: rows,
30091
- permission: sqlString(permission),
30092
- ids
30093
- }) : fillTemplate(`authorization.functions.rowsWithFor`, forUser, {
30094
- user,
30095
- resource: rows,
30096
- permission: sqlString(permission),
30097
- ids
30098
- })} as r(id))`;
30099
- return forUser === void 0 ? `(${user} = auth.uid() and ${member})` : `(${member})`;
30100
- };
30183
+ if (!isResourceName(rows) || typeof permission !== "string" || permission === "") throw new TypeError(`${where} takes { rows, key }: the provider's resource name and the permission key`);
30184
+ return providerRowCheck(ctx, where, rows, permission);
30101
30185
  }
30102
30186
  if (typeof value !== "string" || !QUALIFIED$1.test(value)) throw new TypeError(`${where} must be a schema-qualified function name, such as public.can_read_calendar, or { rows, key }`);
30103
30187
  const fn = value.split(".").map(sqlIdent).join(".");
@@ -30196,7 +30280,25 @@ function eventOwner(ctx) {
30196
30280
  return ctx.has("events", "createdBy") ? ctx.col("events", "createdBy") : void 0;
30197
30281
  }
30198
30282
  const accessCall = (ctx, calendar, action, user = "auth.uid()") => `${ctx.fn("calendar_access")}(${calendar}, ${user}, '${action}')`;
30283
+ const accessForCall = (ctx, calendar, user) => `${ctx.fn("calendar_access_for")}(${calendar}, ${user}, 'read')`;
30284
+ const eventAccessForCall = (ctx, event, user) => `${ctx.fn("calendar_event_access_for")}(${event}, ${user}, 'read')`;
30199
30285
  const eventAccessCall = (ctx, event, action, user = "auth.uid()") => `${ctx.fn("calendar_event_access")}(${event}, ${user}, '${action}')`;
30286
+ const internalGrant = (signature) => `revoke execute on function ${signature} from public, anon, authenticated;`;
30287
+ const callerOnly = (ctx, name, id) => `
30288
+ -- ${name}_for for the caller; another user's access is not theirs to see.
30289
+ create or replace function ${ctx.fn(name)}(${id} uuid, user_id uuid, action text)
30290
+ returns boolean
30291
+ language sql
30292
+ stable
30293
+ security definer
30294
+ set search_path = ''
30295
+ as $$
30296
+ select case
30297
+ when ${name}.user_id is distinct from auth.uid() and auth.role() is distinct from 'service_role' then false
30298
+ else ${ctx.fn(`${name}_for`)}(${name}.${id}, ${name}.user_id, ${name}.action)
30299
+ end
30300
+ $$;
30301
+ ${userGrant(`${ctx.fn(name)}(uuid, uuid, text)`)}`;
30200
30302
  function accessFunctions(ctx) {
30201
30303
  const features = calendarFeatures(ctx);
30202
30304
  if (!features.access) return "";
@@ -30208,25 +30310,27 @@ function accessFunctions(ctx) {
30208
30310
  const events = ctx.table("events");
30209
30311
  const k = (column) => `k.${ctx.col("calendars", column)}`;
30210
30312
  const e = (column) => `e.${ctx.col("events", column)}`;
30211
- const user = "calendar_access.user_id";
30313
+ const user = "calendar_access_for.user_id";
30212
30314
  const can = (key) => ctx.scope.canUser(user, "v_tenant", key);
30213
30315
  const grant = features.grants ? `
30214
30316
  select case when bool_or(${ctx.is("grants", "role", `g.${ctx.col("grants", "role")}`, ["editor"])}) then 'editor' else 'viewer' end
30215
30317
  into v_grant
30216
30318
  from ${ctx.table("grants")} g
30217
- where g.${ctx.col("grants", "calendar")} = calendar_access.calendar_id
30319
+ where g.${ctx.col("grants", "calendar")} = calendar_access_for.calendar_id
30218
30320
  and g.${ctx.col("grants", "user")} = ${user}
30219
30321
  having count(*) > 0;` : "";
30220
30322
  const custom = (fn, actions) => fn === void 0 ? "" : `
30221
- if calendar_access.action in (${actions}) then
30222
- return coalesce(${fn("calendar_access.calendar_id", user)}, false);
30323
+ if calendar_access_for.action in (${actions}) then
30324
+ return coalesce(${fn("calendar_access_for.calendar_id", user)}, false);
30223
30325
  end if;`;
30224
30326
  const owner = eventOwner(ctx);
30225
30327
  return `
30226
30328
  -- Whether user_id may read, write or manage a calendar, or see its private
30227
30329
  -- events: its owner may do all of it; an editor grant writes and sees private
30228
- -- events; on a shared calendar the tenant's keys decide.
30229
- create or replace function ${ctx.fn("calendar_access")}(calendar_id uuid, user_id uuid, action text)
30330
+ -- events; on a shared calendar the tenant's keys decide. It answers for any
30331
+ -- user, so only the block's own functions call it; calendar_access answers
30332
+ -- for the caller.
30333
+ create or replace function ${ctx.fn("calendar_access_for")}(calendar_id uuid, user_id uuid, action text)
30230
30334
  returns boolean
30231
30335
  language plpgsql
30232
30336
  stable
@@ -30246,14 +30350,14 @@ begin
30246
30350
  select ${k("tenant")}, ${ownedBy(ctx, "k.", user)}, ${privateCalendar(ctx, "k.")}
30247
30351
  into v_tenant, v_owner, v_private
30248
30352
  from ${calendars} k
30249
- where ${k("id")} = calendar_access.calendar_id;
30353
+ where ${k("id")} = calendar_access_for.calendar_id;
30250
30354
  if not found or not ${can(read)} then
30251
30355
  return false;
30252
30356
  end if;${custom(features.readFn, "'read'")}${custom(features.writeFn, "'write', 'manage', 'private'")}${custom(features.shareFn ?? features.writeFn, "'share'")}
30253
30357
  if v_owner then
30254
30358
  return true;
30255
30359
  end if;${grant}
30256
- return case calendar_access.action
30360
+ return case calendar_access_for.action
30257
30361
  when 'read' then not v_private or v_grant is not null
30258
30362
  when 'write' then coalesce(v_grant = 'editor', false) or (not v_private and ${can(write)})
30259
30363
  when 'manage' then not v_private and ${can(manage)}
@@ -30263,11 +30367,12 @@ begin
30263
30367
  end;
30264
30368
  end;
30265
30369
  $$;
30266
- ${userGrant(`${ctx.fn("calendar_access")}(uuid, uuid, text)`)}
30370
+ ${internalGrant(`${ctx.fn("calendar_access_for")}(uuid, uuid, text)`)}
30371
+ ${callerOnly(ctx, "calendar_access", "calendar_id")}
30267
30372
 
30268
30373
  -- Whether user_id may read or write one event: the calendar's access, and for
30269
30374
  -- a private event its owner or someone who sees the calendar's private events.
30270
- create or replace function ${ctx.fn("calendar_event_access")}(event_id uuid, user_id uuid, action text)
30375
+ create or replace function ${ctx.fn("calendar_event_access_for")}(event_id uuid, user_id uuid, action text)
30271
30376
  returns boolean
30272
30377
  language plpgsql
30273
30378
  stable
@@ -30280,20 +30385,21 @@ declare
30280
30385
  v_private boolean;
30281
30386
  v_mine boolean;
30282
30387
  begin
30283
- if calendar_event_access.user_id is null then
30388
+ if calendar_event_access_for.user_id is null then
30284
30389
  return auth.role() = 'service_role';
30285
30390
  end if;
30286
- select ${e("calendar")}, ${privateEvent(ctx, "e.")}, ${owner === void 0 ? "false" : `coalesce(e.${owner} = calendar_event_access.user_id, false)`}
30391
+ select ${e("calendar")}, ${privateEvent(ctx, "e.")}, ${owner === void 0 ? "false" : `coalesce(e.${owner} = calendar_event_access_for.user_id, false)`}
30287
30392
  into v_calendar, v_private, v_mine
30288
30393
  from ${events} e
30289
- where ${e("id")} = calendar_event_access.event_id;
30290
- if not found or not ${ctx.fn("calendar_access")}(v_calendar, calendar_event_access.user_id, case when calendar_event_access.action = 'write' then 'write' else 'read' end) then
30394
+ where ${e("id")} = calendar_event_access_for.event_id;
30395
+ if not found or not ${ctx.fn("calendar_access_for")}(v_calendar, calendar_event_access_for.user_id, case when calendar_event_access_for.action = 'write' then 'write' else 'read' end) then
30291
30396
  return false;
30292
30397
  end if;
30293
- return not v_private or v_mine or ${ctx.fn("calendar_access")}(v_calendar, calendar_event_access.user_id, 'private');
30398
+ return not v_private or v_mine or ${ctx.fn("calendar_access_for")}(v_calendar, calendar_event_access_for.user_id, 'private');
30294
30399
  end;
30295
30400
  $$;
30296
- ${userGrant(`${ctx.fn("calendar_event_access")}(uuid, uuid, text)`)}
30401
+ ${internalGrant(`${ctx.fn("calendar_event_access_for")}(uuid, uuid, text)`)}
30402
+ ${callerOnly(ctx, "calendar_event_access", "event_id")}
30297
30403
  `;
30298
30404
  }
30299
30405
  function grantsTable(ctx) {
@@ -31731,7 +31837,7 @@ function feedEvents(ctx, events, calendars, attendees, where, creator) {
31731
31837
  const e = (column) => `e.${ctx.col("events", column)}`;
31732
31838
  const k = (column) => `k.${ctx.col("calendars", column)}`;
31733
31839
  const owner = eventOwner(ctx);
31734
- const visible = feed.visibility === "public" ? `(not ${privateEvent(ctx, "e.")}${owner === void 0 ? "" : ` or e.${owner} = ${creator}`})` : features.access ? eventAccessCall(ctx, e("id"), "read", creator) : "true";
31840
+ const visible = feed.visibility === "public" ? `(not ${privateEvent(ctx, "e.")}${owner === void 0 ? "" : ` or e.${owner} = ${creator}`})` : features.access ? eventAccessForCall(ctx, e("id"), creator) : "true";
31735
31841
  const reminders = ctx.installed("reminders") && ctx.of("reminders").hasTable("reminders") ? (() => {
31736
31842
  const r = ctx.of("reminders");
31737
31843
  const c = (column) => `r.${r.col("reminders", column)}`;
@@ -31790,7 +31896,7 @@ begin
31790
31896
  return null;
31791
31897
  end if;
31792
31898
  v_calendar := v_subject::uuid;
31793
- if v_creator is null or not ${ctx.scope.canUser("v_creator", "v_tenant", read)}${features.access ? ` or not ${accessCall(ctx, "v_calendar", "read", "v_creator")}` : ""} then
31899
+ if v_creator is null or not ${ctx.scope.canUser("v_creator", "v_tenant", read)}${features.access ? ` or not ${accessForCall(ctx, "v_calendar", "v_creator")}` : ""} then
31794
31900
  return null;
31795
31901
  end if;
31796
31902
  ${touchShareLink(s, "v_link")}
@@ -31815,7 +31921,7 @@ function userFeed(ctx, events, calendars, attendees) {
31815
31921
  const l = (column) => `l.${s.col("links", column)}`;
31816
31922
  const k = (column) => `k.${ctx.col("calendars", column)}`;
31817
31923
  const read = ctx.permission("read", moduleOperations("calendar").read);
31818
- const readable = features.access ? accessCall(ctx, k("id"), "read", "v_user") : ctx.scope.canUser("v_user", k("tenant"), read);
31924
+ const readable = features.access ? accessForCall(ctx, k("id"), "v_user") : ctx.scope.canUser("v_user", k("tenant"), read);
31819
31925
  return `
31820
31926
  -- Every calendar the user a share link names can read, with their events, as
31821
31927
  -- one iCal feed. Open to anon: the token is the credential, and each fetch
@@ -56102,9 +56208,12 @@ const DONATIONS = {
56102
56208
  // src/sql/modules/drive-drives.ts
56103
56209
  /** The drives, their sharing and their external connections. */
56104
56210
  function driveDrivesSql(kit) {
56105
- const { ctx, T, n, fn, read, create, manage, roles, typed, teamColumn, drives, driveKinds, driveKindsArray, sources, sourcesArray, D, DG, C, d, dg, c, has, binColumn, sourceColumn, externalColumn, metadataColumn, driveHeld, connectionJson, withDriveRole, driveExpiring, driveGrantLive, driveAudit, connectionAudit, recordDrive, recordConnection, teams, tenant, m, rank, forbidden, touch } = kit;
56106
- const principalTypes = typed ? "('user', 'team', 'role')" : teamColumn ? "('user', 'team')" : "('user')";
56107
- const teamExistsDrive = teams === void 0 ? "false" : `exists (select 1 from ${teams.table("teams")} t where t.${teams.col("teams", "id")}::text = drive_share_drive.principal_id and t.${teams.col("teams", "tenant")} = v_drive.${d("tenant")})`;
56211
+ const { ctx, T, n, fn, read, create, manage, roles, driveTyped, driveTeamColumn, drivePrincipalTypes, drivePrincipalType, drivePrincipalId, drives, driveKinds, driveKindsArray, sources, sourcesArray, D, DG, C, d, dg, c, has, binColumn, sourceColumn, externalColumn, metadataColumn, driveHeld, connectionJson, withDriveRole, driveExpiring, driveGrantLive, driveAudit, connectionAudit, recordDrive, recordConnection, teams, tenant, m, rank, forbidden, touch } = kit;
56212
+ const teamExistsDrive = !drives || teams === void 0 ? "false" : `exists (select 1 from ${teams.table("teams")} t where t.${teams.col("teams", "id")}::text = drive_share_drive.principal_id and t.${teams.col("teams", "tenant")} = v_drive.${d("tenant")})`;
56213
+ const driveTeamValue = drives && driveTeamColumn ? teams === void 0 ? "null" : `case when v_type = 'team' then (select t.${teams.col("teams", "id")} from ${teams.table("teams")} t where t.${teams.col("teams", "id")}::text = drive_share_drive.principal_id and t.${teams.col("teams", "tenant")} = v_drive.${d("tenant")}) end` : void 0;
56214
+ const driveGrantColumns = drives ? driveTyped ? `${dg("tenant")}, ${dg("drive")}, ${dg("principalType")}, ${dg("principalId")}, ${dg("role")}${driveExpiring ? `, ${dg("expiresAt")}` : ""}${ctx.has("driveGrants", "createdBy") ? `, ${dg("createdBy")}` : ""}` : `${dg("tenant")}, ${dg("drive")}, ${dg("user")}${driveTeamColumn ? `, ${dg("team")}` : ""}, ${dg("role")}${driveExpiring ? `, ${dg("expiresAt")}` : ""}${ctx.has("driveGrants", "createdBy") ? `, ${dg("createdBy")}` : ""}` : "";
56215
+ const driveGrantValues = drives ? driveTyped ? `v_drive.${d("tenant")}, v_drive.${d("id")}, v_type, drive_share_drive.principal_id, drive_share_drive.role${driveExpiring ? ", drive_share_drive.expires_at" : ""}${ctx.has("driveGrants", "createdBy") ? ", auth.uid()" : ""}` : `v_drive.${d("tenant")}, v_drive.${d("id")}, case when v_type = 'user' then drive_share_drive.principal_id::uuid end${driveTeamColumn ? `, ${driveTeamValue}` : ""}, drive_share_drive.role${driveExpiring ? ", drive_share_drive.expires_at" : ""}${ctx.has("driveGrants", "createdBy") ? ", auth.uid()" : ""}` : "";
56216
+ const principalError = drives ? driveTyped ? "principal_type must be user, team or role" : driveTeamColumn ? "principal_type must be user or team" : "principal_type must be user" : "";
56108
56217
  return drives ? `
56109
56218
  -- The drives of an organization, with the caller's role on each.
56110
56219
  create or replace function ${fn("drive_create_drive")}(tenant ${ctx.idType}, name text, kind text default null, owner uuid default null, connection uuid default null)
@@ -56303,8 +56412,8 @@ begin
56303
56412
  if ${rank("drive_share_drive.role")} = 0 then
56304
56413
  ${fail$1("DRIVE_ROLE_UNKNOWN", `role must be one of ${roles.all.join(", ")}`, "22023")}
56305
56414
  end if;
56306
- if v_type not in ${principalTypes} or drive_share_drive.principal_id is null then
56307
- ${fail$1("DRIVE_PRINCIPAL_INVALID", "principal_type must be user, team or role", "22023")}
56415
+ if v_type not in ${drivePrincipalTypes} or drive_share_drive.principal_id is null then
56416
+ ${fail$1("DRIVE_PRINCIPAL_INVALID", principalError, "22023")}
56308
56417
  end if;
56309
56418
  if (v_type = 'user' and (drive_share_drive.principal_id !~ ${UUID_TEXT$1} or not exists (
56310
56419
  select 1 from ${tenant.table("memberships")} mu
@@ -56314,9 +56423,9 @@ begin
56314
56423
  ${fail$1("DRIVE_PRINCIPAL_NOT_FOUND", "no member or team of this organization has that id", "P0002")}
56315
56424
  end if;
56316
56425
  delete from ${DG} dg where dg.${dg("drive")} = v_drive.${d("id")}
56317
- and dg.${dg("principalType")} = v_type and dg.${dg("principalId")} = drive_share_drive.principal_id;
56318
- insert into ${DG} (${dg("tenant")}, ${dg("drive")}, ${dg("principalType")}, ${dg("principalId")}, ${dg("role")}${driveExpiring ? `, ${dg("expiresAt")}` : ""}${ctx.has("driveGrants", "createdBy") ? `, ${dg("createdBy")}` : ""})
56319
- values (v_drive.${d("tenant")}, v_drive.${d("id")}, v_type, drive_share_drive.principal_id, drive_share_drive.role${driveExpiring ? ", drive_share_drive.expires_at" : ""}${ctx.has("driveGrants", "createdBy") ? ", auth.uid()" : ""})
56426
+ and ${drivePrincipalType("dg")} = v_type and ${drivePrincipalId("dg")} = drive_share_drive.principal_id;
56427
+ insert into ${DG} (${driveGrantColumns})
56428
+ values (${driveGrantValues})
56320
56429
  returning ${dg("id")} into v_id;
56321
56430
  ${recordDrive("drive.shared", "v_drive", ", 'principalType', v_type, 'principalId', drive_share_drive.principal_id, 'role', drive_share_drive.role", driveAudit("v_drive", "shared"))}
56322
56431
  return jsonb_build_object('id', v_id, 'driveId', v_drive.${d("id")}, 'principalType', v_type, 'principalId', drive_share_drive.principal_id, 'role', drive_share_drive.role, 'expiresAt', drive_share_drive.expires_at);
@@ -56344,7 +56453,7 @@ begin
56344
56453
  end if;
56345
56454
  ${READ_ONLY_GUARD}
56346
56455
  delete from ${DG} dg where dg.${dg("drive")} = v_drive.${d("id")}
56347
- and dg.${dg("principalType")} = v_type and dg.${dg("principalId")} = drive_unshare_drive.principal_id;
56456
+ and ${drivePrincipalType("dg")} = v_type and ${drivePrincipalId("dg")} = drive_unshare_drive.principal_id;
56348
56457
  if not found then
56349
56458
  return false;
56350
56459
  end if;
@@ -56367,7 +56476,7 @@ begin
56367
56476
  ${fail$1("DRIVE_NOT_FOUND", "drive not found", "P0002")}
56368
56477
  end if;
56369
56478
  return (
56370
- select coalesce(jsonb_agg(jsonb_build_object('id', dg.${dg("id")}, 'driveId', dg.${dg("drive")}, 'principalType', dg.${dg("principalType")}, 'principalId', dg.${dg("principalId")}, 'role', dg.${dg("role")}, 'expiresAt', ${driveExpiring ? `dg.${dg("expiresAt")}` : "null"}) order by ${rank(`dg.${dg("role")}`)} desc, dg.${dg("id")}), '[]'::jsonb)
56479
+ select coalesce(jsonb_agg(jsonb_build_object('id', dg.${dg("id")}, 'driveId', dg.${dg("drive")}, 'principalType', ${drivePrincipalType("dg")}, 'principalId', ${drivePrincipalId("dg")}, 'role', dg.${dg("role")}, 'expiresAt', ${driveExpiring ? `dg.${dg("expiresAt")}` : "null"}) order by ${rank(`dg.${dg("role")}`)} desc, dg.${dg("id")}), '[]'::jsonb)
56371
56480
  from ${DG} dg
56372
56481
  where dg.${dg("drive")} = drive_grants_for_drive.drive${driveGrantLive("dg")}
56373
56482
  );
@@ -56775,8 +56884,8 @@ ${userGrant(`${fn("drive_release_hold")}(uuid)`)}
56775
56884
  // src/sql/modules/drive-tables.ts
56776
56885
  /** The drive tables and the triggers that keep paths and drives in step. */
56777
56886
  function driveTablesSql(kit) {
56778
- const { ctx, T, G, n, g, read, driveKinds, driveKindsArray, sourcesArray, drives, D, DG, C, d, dg, c, extras, sourceColumn, externalColumn, metadataColumn, holdColumn, binColumn, rolesArray } = kit;
56779
- return `${drives && ctx.owns("connections") && C !== void 0 ? `create table if not exists ${C} (
56887
+ const { ctx, T, G, n, g, read, driveKinds, driveKindsArray, sourcesArray, drives, D, DG, C, d, dg, c, extras, sourceColumn, externalColumn, metadataColumn, holdColumn, binColumn, rolesArray, typed, teamColumn, driveColumn, driveTyped, driveTeamColumn } = kit;
56888
+ const connectionTable = drives && ctx.owns("connections") && C !== void 0 ? `create table if not exists ${C} (
56780
56889
  ${c("id")} uuid primary key default gen_random_uuid(),
56781
56890
  ${c("tenant")} ${ctx.idType} not null,
56782
56891
  ${c("user")} uuid not null,
@@ -56805,7 +56914,8 @@ ${renderPolicy(policy$1({
56805
56914
  drop: true,
56806
56915
  target: C
56807
56916
  })}
56808
- ` : ""}${drives && ctx.owns("drives") && D !== void 0 ? `create table if not exists ${D} (
56917
+ ` : "";
56918
+ const driveTable = drives && ctx.owns("drives") && D !== void 0 ? `create table if not exists ${D} (
56809
56919
  ${d("id")} uuid primary key default gen_random_uuid(),
56810
56920
  ${d("tenant")} ${ctx.idType} not null,
56811
56921
  ${d("name")} text not null check (length(btrim(${d("name")})) between 1 and 255),
@@ -56822,26 +56932,36 @@ create index if not exists ${sqlIdent(`${ctx.tableName("drives").name}_kind_idx`
56822
56932
  create index if not exists ${sqlIdent(`${ctx.tableName("drives").name}_owner_idx`)} on ${D} (${d("owner")}) where ${d("owner")} is not null;
56823
56933
  create index if not exists ${sqlIdent(`${ctx.tableName("drives").name}_connection_idx`)} on ${D} (${d("connection")}) where ${d("connection")} is not null;
56824
56934
  ${lockTable(D, { read: true })}
56825
- ` : ""}${drives && ctx.owns("driveGrants") && DG !== void 0 && D !== void 0 ? `create table if not exists ${DG} (
56935
+ ` : "";
56936
+ const driveGrantIdentity = drives && DG !== void 0 ? driveTyped ? ` ${dg("principalType")} text not null check (${dg("principalType")} in ('user', 'team', 'role')),
56937
+ ${dg("principalId")} text not null,` : ` ${dg("user")} uuid${driveTeamColumn ? "" : " not null"},${driveTeamColumn ? `
56938
+ ${dg("team")} uuid,
56939
+ check ((${dg("user")} is not null)::int + (${dg("team")} is not null)::int = 1),` : ""}` : "";
56940
+ const driveGrantUnique = drives && DG !== void 0 && driveTyped ? ` unique (${dg("drive")}, ${dg("principalType")}, ${dg("principalId")}),
56941
+ ` : "";
56942
+ const driveGrantIndexes = drives && DG !== void 0 ? driveTyped ? `create index if not exists ${sqlIdent(`${ctx.tableName("driveGrants").name}_principal_idx`)} on ${DG} (${dg("principalType")}, ${dg("principalId")});` : `create unique index if not exists ${sqlIdent(`${ctx.tableName("driveGrants").name}_user_idx`)} on ${DG} (${dg("drive")}, ${dg("user")}) where ${dg("user")} is not null;
56943
+ create index if not exists ${sqlIdent(`${ctx.tableName("driveGrants").name}_user_principal_idx`)} on ${DG} (${dg("user")}) where ${dg("user")} is not null;${driveTeamColumn ? `
56944
+ create unique index if not exists ${sqlIdent(`${ctx.tableName("driveGrants").name}_team_idx`)} on ${DG} (${dg("drive")}, ${dg("team")}) where ${dg("team")} is not null;
56945
+ create index if not exists ${sqlIdent(`${ctx.tableName("driveGrants").name}_team_principal_idx`)} on ${DG} (${dg("team")}) where ${dg("team")} is not null;` : ""}` : "";
56946
+ const driveGrantTable = drives && ctx.owns("driveGrants") && DG !== void 0 && D !== void 0 ? `create table if not exists ${DG} (
56826
56947
  ${dg("id")} uuid primary key default gen_random_uuid(),
56827
56948
  ${dg("tenant")} ${ctx.idType} not null,
56828
56949
  ${dg("drive")} uuid not null,
56829
- ${dg("principalType")} text not null check (${dg("principalType")} in ('user', 'team', 'role')),
56830
- ${dg("principalId")} text not null,
56950
+ ${driveGrantIdentity}
56831
56951
  ${dg("role")} text not null,
56832
56952
  ${dg("expiresAt")} timestamptz,
56833
56953
  ${dg("createdBy")} uuid default auth.uid(),
56834
56954
  ${dg("createdAt")} timestamptz not null default now(),
56835
- unique (${dg("drive")}, ${dg("principalType")}, ${dg("principalId")}),
56836
- foreign key (${dg("drive")}, ${dg("tenant")}) references ${D} (${d("id")}, ${d("tenant")}) on delete cascade
56955
+ ${driveGrantUnique} foreign key (${dg("drive")}, ${dg("tenant")}) references ${D} (${d("id")}, ${d("tenant")}) on delete cascade
56837
56956
  );
56838
- create index if not exists ${sqlIdent(`${ctx.tableName("driveGrants").name}_principal_idx`)} on ${DG} (${dg("principalType")}, ${dg("principalId")});
56957
+ ${driveGrantIndexes}
56839
56958
  ${ensureCheck(DG, "bsb_drive_drive_grants_role", `${dg("role")} = any (${rolesArray})`)}
56840
56959
  ${lockTable(DG, { read: true })}
56841
- ` : ""}${ctx.owns("nodes") ? `create table if not exists ${T} (
56960
+ ` : "";
56961
+ const nodeTable = ctx.owns("nodes") ? `create table if not exists ${T} (
56842
56962
  ${n("id")} uuid primary key default gen_random_uuid(),
56843
56963
  ${n("tenant")} ${ctx.idType} not null,
56844
- ${drives ? `${n("drive")} uuid not null,` : ""}
56964
+ ${driveColumn ? `${n("drive")} uuid not null,` : ""}
56845
56965
  ${n("parent")} uuid references ${T} (${n("id")}) on delete cascade,
56846
56966
  ${n("kind")} text not null check (${n("kind")} in ('folder', 'file')),
56847
56967
  ${n("name")} text not null check (length(btrim(${n("name")})) between 1 and 255 and ${n("name")} !~ '[/[:cntrl:]]'),
@@ -56859,27 +56979,35 @@ ${lockTable(DG, { read: true })}
56859
56979
  foreign key (${n("drive")}, ${n("tenant")}) references ${D} (${d("id")}, ${d("tenant")}) on delete cascade` : ""}${externalColumn && sourceColumn ? `,
56860
56980
  check (${n("externalId")} is null or ${n("source")} <> 'internal')` : ""}
56861
56981
  );${addExtraColumns(T, extras)}
56862
- create unique index if not exists ${sqlIdent(`${ctx.tableName("nodes").name}_sibling_name_idx`)} on ${T} (${n("tenant")}${drives ? `, ${n("drive")}` : ""}, coalesce(${n("parent")}, '00000000-0000-0000-0000-000000000000'::uuid), lower(${n("name")})) where ${n("deletedAt")} is null${sourceColumn ? ` and ${n("source")} = 'internal'` : ""};
56863
- create index if not exists ${sqlIdent(`${ctx.tableName("nodes").name}_parent_idx`)} on ${T} (${n("tenant")}${drives ? `, ${n("drive")}` : ""}, ${n("parent")}, ${n("rank")});
56982
+ create unique index if not exists ${sqlIdent(`${ctx.tableName("nodes").name}_sibling_name_idx`)} on ${T} (${n("tenant")}${driveColumn ? `, ${n("drive")}` : ""}, coalesce(${n("parent")}, '00000000-0000-0000-0000-000000000000'::uuid), lower(${n("name")})) where ${n("deletedAt")} is null${sourceColumn ? ` and ${n("source")} = 'internal'` : ""};
56983
+ create index if not exists ${sqlIdent(`${ctx.tableName("nodes").name}_parent_idx`)} on ${T} (${n("tenant")}${driveColumn ? `, ${n("drive")}` : ""}, ${n("parent")}, ${n("rank")});
56864
56984
  create index if not exists ${sqlIdent(`${ctx.tableName("nodes").name}_parent_fk_idx`)} on ${T} (${n("parent")}) where ${n("parent")} is not null;
56865
56985
  create index if not exists ${sqlIdent(`${ctx.tableName("nodes").name}_path_idx`)} on ${T} (${n("path")} text_pattern_ops);
56866
- create index if not exists ${sqlIdent(`${ctx.tableName("nodes").name}_attachment_idx`)} on ${T} (${n("attachment")});${drives ? `
56986
+ create index if not exists ${sqlIdent(`${ctx.tableName("nodes").name}_attachment_idx`)} on ${T} (${n("attachment")});${driveColumn ? `
56867
56987
  create index if not exists ${sqlIdent(`${ctx.tableName("nodes").name}_drive_idx`)} on ${T} (${n("tenant")}, ${n("drive")}, ${n("parent")}, ${n("rank")});` : ""}${externalColumn ? `
56868
- create unique index if not exists ${sqlIdent(`${ctx.tableName("nodes").name}_external_idx`)} on ${T} (${drives ? `${n("drive")}, ` : `${n("tenant")}, `}${n("source")}, ${n("externalId")}) where ${n("externalId")} is not null${binColumn ? ` and ${n("deletedAt")} is null` : ""};` : ""}
56988
+ create unique index if not exists ${sqlIdent(`${ctx.tableName("nodes").name}_external_idx`)} on ${T} (${driveColumn ? `${n("drive")}, ` : `${n("tenant")}, `}${n("source")}, ${n("externalId")}) where ${n("externalId")} is not null${binColumn ? ` and ${n("deletedAt")} is null` : ""};` : ""}
56869
56989
  ${lockTable(T, { read: true })}
56870
- ` : ""}${ctx.owns("grants") ? `create table if not exists ${G} (
56990
+ ` : "";
56991
+ const grantIdentity = ctx.owns("grants") ? typed ? ` ${g("principalType")} text not null check (${g("principalType")} in ('user', 'team', 'role')),
56992
+ ${g("principalId")} text not null,` : ` ${g("user")} uuid${teamColumn ? "" : " not null"},${teamColumn ? `
56993
+ ${g("team")} uuid,
56994
+ check ((${g("user")} is not null)::int + (${g("team")} is not null)::int = 1),` : ""}` : "";
56995
+ const grantUnique = ctx.owns("grants") && typed ? ` unique (${g("node")}, ${g("principalType")}, ${g("principalId")})` : "";
56996
+ const grantIndexes = ctx.owns("grants") ? typed ? `create index if not exists ${sqlIdent(`${ctx.tableName("grants").name}_principal_idx`)} on ${G} (${g("principalType")}, ${g("principalId")});` : `create unique index if not exists ${sqlIdent(`${ctx.tableName("grants").name}_user_idx`)} on ${G} (${g("node")}, ${g("user")}) where ${g("user")} is not null;
56997
+ create index if not exists ${sqlIdent(`${ctx.tableName("grants").name}_user_principal_idx`)} on ${G} (${g("user")}) where ${g("user")} is not null;${teamColumn ? `
56998
+ create unique index if not exists ${sqlIdent(`${ctx.tableName("grants").name}_team_idx`)} on ${G} (${g("node")}, ${g("team")}) where ${g("team")} is not null;
56999
+ create index if not exists ${sqlIdent(`${ctx.tableName("grants").name}_team_principal_idx`)} on ${G} (${g("team")}) where ${g("team")} is not null;` : ""}` : "";
57000
+ return `${connectionTable}${driveTable}${driveGrantTable}${nodeTable}${ctx.owns("grants") ? `create table if not exists ${G} (
56871
57001
  ${g("id")} uuid primary key default gen_random_uuid(),
56872
57002
  ${g("tenant")} ${ctx.idType} not null,
56873
57003
  ${g("node")} uuid not null references ${T} (${n("id")}) on delete cascade,
56874
- ${g("principalType")} text not null check (${g("principalType")} in ('user', 'team', 'role')),
56875
- ${g("principalId")} text not null,
57004
+ ${grantIdentity}
56876
57005
  ${g("role")} text not null,
56877
57006
  ${g("expiresAt")} timestamptz,
56878
57007
  ${g("createdBy")} uuid default auth.uid(),
56879
- ${g("createdAt")} timestamptz not null default now(),
56880
- unique (${g("node")}, ${g("principalType")}, ${g("principalId")})
56881
- );
56882
- create index if not exists ${sqlIdent(`${ctx.tableName("grants").name}_principal_idx`)} on ${G} (${g("principalType")}, ${g("principalId")});
57008
+ ${g("createdAt")} timestamptz not null default now()${grantUnique ? "," : ""}
57009
+ ${grantUnique ? `${grantUnique}\n` : ""});
57010
+ ${grantIndexes}
56883
57011
  ${ensureCheck(G, "bsb_drive_grants_role", `${g("role")} = any (${rolesArray})`)}
56884
57012
  ${lockTable(G, { read: false })}
56885
57013
  ` : ""}`;
@@ -57004,7 +57132,7 @@ create trigger ${ctx.trigger("drive_node_drive_cascade")}
57004
57132
  // src/sql/modules/drive-core.ts
57005
57133
  /** The tree, grants and sharing: the drive module. */
57006
57134
  function driveCoreSql(kit) {
57007
- const { ctx, T, G, n, g, fn, read, create, manage, roles, conflict, pathMode, ranked, drives, D, DG, d, dg, readOnly, held, driveGrantLive, rolesArray, rank, live, canRead, canWrite, canShare, notFound, forbidden, record, dataAudit, principalMatch, grantLive, nodeJson, withRole, orderBy, touch, insertColumns, insertValues, directGrant, siblings } = kit;
57135
+ const { ctx, T, G, n, g, fn, read, create, manage, roles, conflict, pathMode, ranked, drives, D, DG, d, dg, readOnly, held, driveGrantLive, rolesArray, rank, live, canRead, canWrite, canShare, notFound, forbidden, record, dataAudit, principalMatch, drivePrincipalMatch, grantLive, nodeJson, withRole, orderBy, touch, insertColumns, insertValues, directGrant, siblings, nodeRole, driveRole, readPolicy, driveColumn } = kit;
57008
57136
  const tables = driveTablesSql(kit);
57009
57137
  const ancestors = pathMode ? ` select string_to_array(btrim(x.${n("path")}, '/'), '/')::uuid[] from ${T} x where x.${n("id")} = drive_ancestors.node` : ` with recursive up (id, parent, depth) as (
57010
57138
  select x.${n("id")}, x.${n("parent")}, 0 from ${T} x where x.${n("id")} = drive_ancestors.node
@@ -57063,9 +57191,7 @@ as $$
57063
57191
  $$;
57064
57192
  ${userGrant(`${fn("drive_node_held")}(uuid)`)}
57065
57193
  ${drives ? `
57066
- -- The caller's role on a drive: ${OPERATIONS["drive.manage"]} is ${roles.top},
57067
- -- the owner holds ${roles.top} too${roles.member === void 0 ? "" : `, options.memberRole (${roles.member}) covers every member with ${OPERATIONS["drive.read"]}`}, and a grant that names them or one of their teams
57068
- -- adds its role. ${OPERATIONS["drive.read"]} in the drive's organization is required.
57194
+ -- The caller's role on a drive: ${driveRole === void 0 ? `${OPERATIONS["drive.manage"]} is ${roles.top}, the owner holds ${roles.top} too${roles.member === void 0 ? "" : `, options.memberRole (${roles.member}) covers every member with ${OPERATIONS["drive.read"]}`}, and a grant that names them or one of their teams adds its role` : `options.roleFunctions.drive (${driveRole.label}) decides it`}. ${OPERATIONS["drive.read"]} in the drive's organization is required.
57069
57195
  create or replace function ${fn("drive_drive_role")}(drive uuid)
57070
57196
  returns text
57071
57197
  language plpgsql
@@ -57086,13 +57212,13 @@ begin
57086
57212
  select d.${d("tenant")}, d.${d("owner")} into v_tenant, v_owner from ${D} d where d.${d("id")} = drive_drive_role.drive;
57087
57213
  if v_tenant is null or v_uid is null or not ${ctx.can("tenant", "v_tenant", read)} then
57088
57214
  return null;
57089
- end if;
57215
+ end if;${driveRole === void 0 ? "" : `\n return (select r from (select ${driveRole.role("drive_drive_role.drive", "v_uid")}) x(r) where r = any (${rolesArray}));`}
57090
57216
  if ${ctx.can("tenant", "v_tenant", manage)} or v_owner = v_uid then
57091
57217
  return ${sqlString(roles.top)};
57092
57218
  end if;
57093
57219
  select max(${rank(`dg.${dg("role")}`)}) into v_rank from ${DG} dg
57094
57220
  where dg.${dg("drive")} = drive_drive_role.drive${driveGrantLive("dg")}
57095
- and ${principalMatch("dg", "v_uid", "v_tenant")};
57221
+ and ${drivePrincipalMatch("dg", "v_uid", "v_tenant")};
57096
57222
  ${roles.member === void 0 ? "" : `v_rank := greatest(coalesce(v_rank, 0), ${rank(sqlString(roles.member))});`}
57097
57223
  if coalesce(v_rank, 0) = 0 then
57098
57224
  return null;
@@ -57122,7 +57248,7 @@ stable
57122
57248
  security definer
57123
57249
  set search_path = ''
57124
57250
  as $$
57125
- select d.${d("id")} from ${D} d
57251
+ ${driveRole === void 0 ? ` select d.${d("id")} from ${D} d
57126
57252
  where ${SERVICE_CALLER$1}
57127
57253
  or (auth.uid() is not null
57128
57254
  and d.${d("tenant")} in (select ${ctx.scope.ids(read)})
@@ -57134,13 +57260,16 @@ as $$
57134
57260
  and ${rank(`dg.${dg("role")}`)} >= ${rank(sqlString(roles.read))}
57135
57261
  and ${rank(sqlString(roles.read))} > 0
57136
57262
  and d.${d("tenant")} in (select ${ctx.scope.ids(read)})
57137
- and ${principalMatch("dg", "auth.uid()", `d.${d("tenant")}`)}
57263
+ and ${drivePrincipalMatch("dg", "auth.uid()", `d.${d("tenant")}`)}` : ` select d.${d("id")} from ${D} d
57264
+ where ${SERVICE_CALLER$1}
57265
+ or (auth.uid() is not null
57266
+ and d.${d("tenant")} in (select ${ctx.scope.ids(read)})
57267
+ and (${driveRole.role(`d.${d("id")}`, "auth.uid()")}) = any (${rolesArray}))`}
57138
57268
  $$;
57139
57269
  ${userGrant(`${fn("drive_drive_readable_ids")}()`)}
57140
57270
  ` : ""}
57141
57271
 
57142
- -- The caller's role on a node: the highest of the grants on it and its
57143
- -- ancestors that name them, one of their teams or their organization role${roles.member === void 0 ? "" : `, and options.memberRole (${roles.member}) for every member with ${OPERATIONS["drive.read"]}`}. ${OPERATIONS["drive.manage"]} is ${roles.top} everywhere. Grants
57272
+ -- The caller's role on a node: ${nodeRole === void 0 ? `the highest of the grants on it and its ancestors that name them, one of their teams or their organization role${roles.member === void 0 ? "" : `, and options.memberRole (${roles.member}) for every member with ${OPERATIONS["drive.read"]}`}. ${OPERATIONS["drive.manage"]} is ${roles.top} everywhere` : `options.roleFunctions.node (${nodeRole.label}) decides it`}. Grants
57144
57273
  -- need ${OPERATIONS["drive.read"]} in the node's organization too.
57145
57274
  create or replace function ${fn("drive_role")}(node uuid)
57146
57275
  returns text
@@ -57162,7 +57291,7 @@ begin
57162
57291
  select x.${n("tenant")}${drives ? `, x.${n("drive")}` : ""} into v_tenant${drives ? ", v_drive" : ""} from ${T} x where x.${n("id")} = drive_role.node;
57163
57292
  if v_tenant is null or v_uid is null or not ${ctx.can("tenant", "v_tenant", read)} then
57164
57293
  return null;
57165
- end if;
57294
+ end if;${nodeRole === void 0 ? "" : `\n return (select r from (select ${nodeRole.role("drive_role.node", "v_uid")}) x(r) where r = any (${rolesArray}));`}
57166
57295
  if ${ctx.can("tenant", "v_tenant", manage)} then
57167
57296
  return ${sqlString(roles.top)};
57168
57297
  end if;
@@ -57216,7 +57345,7 @@ stable
57216
57345
  security definer
57217
57346
  set search_path = ''
57218
57347
  as $$
57219
- select x.${n("id")} from ${T} x
57348
+ ${nodeRole === void 0 ? ` select x.${n("id")} from ${T} x
57220
57349
  where ${SERVICE_CALLER$1}
57221
57350
  or (auth.uid() is not null
57222
57351
  and x.${n("tenant")} in (select ${ctx.scope.ids(read)})
@@ -57243,7 +57372,11 @@ as $$
57243
57372
  and ${rank(`dg.${dg("role")}`)} >= ${rank(sqlString(roles.read))}
57244
57373
  and ${rank(sqlString(roles.read))} > 0
57245
57374
  and x.${n("tenant")} in (select ${ctx.scope.ids(read)})
57246
- and ${principalMatch("dg", "auth.uid()", `x.${n("tenant")}`)}` : ""}
57375
+ and ${drivePrincipalMatch("dg", "auth.uid()", `x.${n("tenant")}`)}` : ""}` : ` select x.${n("id")} from ${T} x
57376
+ where ${SERVICE_CALLER$1}
57377
+ or (auth.uid() is not null
57378
+ and x.${n("tenant")} in (select ${ctx.scope.ids(read)})
57379
+ and (${nodeRole.role(`x.${n("id")}`, "auth.uid()")}) = any (${rolesArray}))`}
57247
57380
  $$;
57248
57381
  ${userGrant(`${fn("drive_readable_ids")}()`)}
57249
57382
 
@@ -57257,7 +57390,7 @@ as $$
57257
57390
  select ${nodeJson("")}
57258
57391
  $$;
57259
57392
  revoke execute on function ${fn("drive_node_json")}(${T}) from public, anon, authenticated;
57260
- ${ctx.manages ? `
57393
+ ${ctx.manages && readPolicy ? `
57261
57394
  ${renderPolicy(policy$1({
57262
57395
  table: T,
57263
57396
  name: ctx.naming.rename("drive_nodes_read"),
@@ -57268,7 +57401,7 @@ ${renderPolicy(policy$1({
57268
57401
  drop: true,
57269
57402
  target: T
57270
57403
  })}
57271
- ` : ""}${drives && D !== void 0 && ctx.owns("drives") ? `
57404
+ ` : ""}${readPolicy && drives && D !== void 0 && ctx.owns("drives") ? `
57272
57405
  ${renderPolicy(policy$1({
57273
57406
  table: D,
57274
57407
  name: ctx.naming.rename("drive_drives_read"),
@@ -57279,7 +57412,7 @@ ${renderPolicy(policy$1({
57279
57412
  drop: true,
57280
57413
  target: D
57281
57414
  })}
57282
- ` : ""}${drives && DG !== void 0 && ctx.owns("driveGrants") ? `
57415
+ ` : ""}${readPolicy && drives && DG !== void 0 && ctx.owns("driveGrants") ? `
57283
57416
  ${renderPolicy(policy$1({
57284
57417
  table: DG,
57285
57418
  name: ctx.naming.rename("drive_drive_grants_read"),
@@ -57445,7 +57578,7 @@ declare
57445
57578
  v_name text;
57446
57579
  v_last text;
57447
57580
  begin
57448
- select * into v_parent from ${T} x where x.${n("id")} = drive_insert_node.parent;${drives ? `
57581
+ select * into v_parent from ${T} x where x.${n("id")} = drive_insert_node.parent;${driveColumn ? `
57449
57582
  if drive_insert_node.parent is not null then
57450
57583
  v_drive := v_parent.${n("drive")};
57451
57584
  end if;` : ""}
@@ -57630,7 +57763,7 @@ begin
57630
57763
  if v_name = v_node.${n("name")} then
57631
57764
  return ${withRole("v_node")};
57632
57765
  end if;
57633
- v_name := ${fn("drive_free_name")}(v_node.${n("tenant")}, ${drives ? `v_node.${n("drive")}` : "null"}, v_node.${n("parent")}, v_name, v_node.${n("id")},
57766
+ v_name := ${fn("drive_free_name")}(v_node.${n("tenant")}, ${driveColumn ? `v_node.${n("drive")}` : "null"}, v_node.${n("parent")}, v_name, v_node.${n("id")},
57634
57767
  case when ${fn("drive_conflict")}(drive_rename.conflict) = 'rename' then 'rename' else 'fail' end);
57635
57768
  ${ctx.hook("before_drive_node_rename", [["uuid", `v_node.${n("id")}`], ["text", "v_name"]])}
57636
57769
  v_previous := v_node.${n("name")};
@@ -57676,8 +57809,8 @@ begin
57676
57809
  ${fail$1("DRIVE_RANK_INVALID", "rank must be a key from rankBetween", "22023")}
57677
57810
  end if;` : ""}
57678
57811
  v_previous := v_node.${n("parent")};
57679
- if drive_move.parent is null then${drives ? `
57680
- v_target := coalesce(drive_move.drive, v_node.${n("drive")});
57812
+ if drive_move.parent is null then${driveColumn ? `
57813
+ v_target := coalesce(drive_move.drive, v_node.${n("drive")});` : ""}${drives ? `
57681
57814
  if v_target is null then
57682
57815
  ${fail$1("DRIVE_REQUIRED", "a top-level item needs a drive", "22023")}
57683
57816
  end if;
@@ -57701,14 +57834,14 @@ begin
57701
57834
  perform ${fn("drive_check_parent")}(v_node.${n("tenant")}, drive_move.parent, drive_move.drive);
57702
57835
  if v_node.${n("id")} = any (${fn("drive_ancestors")}(drive_move.parent)) then
57703
57836
  ${fail$1("DRIVE_MOVE_CYCLE", "a folder can't move into itself or its own subfolder", "22023")}
57704
- end if;${drives ? `
57705
- select x.${n("drive")} into v_target from ${T} x where x.${n("id")} = drive_move.parent;
57837
+ end if;${driveColumn ? `
57838
+ select x.${n("drive")} into v_target from ${T} x where x.${n("id")} = drive_move.parent;` : ""}${drives ? `
57706
57839
  if v_target is distinct from v_node.${n("drive")} and not (${SERVICE_CALLER$1} or ${canShare(`v_node.${n("id")}`)}) then
57707
57840
  ${forbidden("move this item to another drive")}
57708
57841
  end if;` : ""}
57709
57842
  end if;
57710
57843
  ${ctx.hook("before_drive_node_move", [["uuid", `v_node.${n("id")}`], ["uuid", "drive_move.parent"]])}
57711
- if v_previous is distinct from drive_move.parent${drives ? ` or v_target is distinct from v_node.${n("drive")}` : ""} then
57844
+ if v_previous is distinct from drive_move.parent${driveColumn ? ` or v_target is distinct from v_node.${n("drive")}` : ""} then
57712
57845
  v_name := ${fn("drive_free_name")}(v_node.${n("tenant")}, v_target, drive_move.parent, v_node.${n("name")}, v_node.${n("id")},
57713
57846
  case when ${fn("drive_conflict")}(drive_move.conflict) = 'rename' then 'rename' else 'fail' end);
57714
57847
  if drive_move.parent is null and auth.uid() is not null then
@@ -57719,7 +57852,7 @@ begin
57719
57852
  select max(x.${n("rank")}) into v_last from ${T} x
57720
57853
  where ${siblings("x", `v_node.${n("tenant")}`, "drive_move.parent", "v_target")};
57721
57854
  end if;` : ""}
57722
- update ${T} x set ${n("parent")} = drive_move.parent, ${n("name")} = v_name${drives ? `, ${n("drive")} = v_target` : ""}${ranked ? `, ${n("rank")} = coalesce(drive_move.rank, ${rankAfter("v_last")})` : ""}${touch}
57855
+ update ${T} x set ${n("parent")} = drive_move.parent, ${n("name")} = v_name${driveColumn ? `, ${n("drive")} = v_target` : ""}${ranked ? `, ${n("rank")} = coalesce(drive_move.rank, ${rankAfter("v_last")})` : ""}${touch}
57723
57856
  where x.${n("id")} = v_node.${n("id")}
57724
57857
  returning * into v_node;
57725
57858
  ${record("drive.node_moved", "v_node", `, 'parentId', v_node.${n("parent")}, 'previousParentId', v_previous`, dataAudit("v_node", "moved"))}
@@ -57777,7 +57910,7 @@ ${driveDrivesSql(kit)}
57777
57910
  const APPROVE = "'approve'";
57778
57911
  /** Files, revisions, the bin, stars and links: the drive-files module. */
57779
57912
  function driveFilesSql(kit) {
57780
- const { ctx, own, T, G, n, g, fn, read, drives, readOnly, typeLit, attachments, A, a, versions, v, trash, ti, shareLinks, state, st, live, canRead, canWrite, canShare, notFound, forbidden, record, dataAudit, fileJson, nodeJson, json, withRole, orderBy, touch, siblings } = kit;
57913
+ const { ctx, own, T, G, n, g, fn, read, driveColumn, readOnly, typeLit, attachments, A, a, versions, v, trash, ti, shareLinks, state, st, live, canRead, canWrite, canShare, notFound, forbidden, record, dataAudit, fileJson, nodeJson, json, withRole, orderBy, touch, siblings } = kit;
57781
57914
  const tags = labelTags(own);
57782
57915
  const approvals = A !== void 0 && own.installed("approvals") && own.of("approvals").mode !== "custom" ? own.of("approvals") : void 0;
57783
57916
  const tg = (column) => tags === void 0 ? column : tags.col("taggings", column);
@@ -57818,7 +57951,7 @@ declare
57818
57951
  v_node ${T}%rowtype;
57819
57952
  begin
57820
57953
  ${READ_ONLY_GUARD}
57821
- perform ${fn("drive_check_parent")}(drive_create_file.tenant, drive_create_file.parent, drive_create_file.drive);${drives ? `
57954
+ perform ${fn("drive_check_parent")}(drive_create_file.tenant, drive_create_file.parent, drive_create_file.drive);${driveColumn ? `
57822
57955
  if drive_create_file.parent is not null then
57823
57956
  select x.${n("drive")} into v_drive from ${T} x where x.${n("id")} = drive_create_file.parent;
57824
57957
  end if;` : ""}
@@ -58216,7 +58349,7 @@ begin
58216
58349
  ) then
58217
58350
  ${fail$1("DRIVE_PARENT_TRASHED", "restore the folder this item was in first", "22023")}
58218
58351
  end if;
58219
- v_name := ${fn("drive_free_name")}(v_node.${n("tenant")}, ${drives ? `v_node.${n("drive")}` : "null"}, v_node.${n("parent")}, v_node.${n("name")}, v_node.${n("id")}, ${fn("drive_conflict")}(drive_restore.conflict));
58352
+ v_name := ${fn("drive_free_name")}(v_node.${n("tenant")}, ${driveColumn ? `v_node.${n("drive")}` : "null"}, v_node.${n("parent")}, v_node.${n("name")}, v_node.${n("id")}, ${fn("drive_conflict")}(drive_restore.conflict));
58220
58353
  if v_name <> v_node.${n("name")} then
58221
58354
  update ${T} x set ${n("name")} = v_name where x.${n("id")} = v_node.${n("id")};
58222
58355
  end if;