@webiny/api-core-sql 0.0.0-unstable.33e4fd9647 → 0.0.0-unstable.3fddf667ea

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 (80) hide show
  1. package/TableManager.d.ts +29 -12
  2. package/TableManager.js +29 -29
  3. package/TableManager.js.map +1 -1
  4. package/adminUsers/index.js +20 -17
  5. package/adminUsers/index.js.map +1 -1
  6. package/connection/SqlConnectionFeature.d.ts +28 -0
  7. package/connection/SqlConnectionFeature.js +26 -0
  8. package/connection/SqlConnectionFeature.js.map +1 -0
  9. package/connection/index.d.ts +2 -0
  10. package/connection/index.js +1 -0
  11. package/connectionRetry/index.d.ts +3 -0
  12. package/connectionRetry/index.js +2 -0
  13. package/connectionRetry/isConnectionError.d.ts +1 -0
  14. package/connectionRetry/isConnectionError.js +28 -0
  15. package/connectionRetry/isConnectionError.js.map +1 -0
  16. package/connectionRetry/withPgConnectionRetry.d.ts +49 -0
  17. package/connectionRetry/withPgConnectionRetry.js +175 -0
  18. package/connectionRetry/withPgConnectionRetry.js.map +1 -0
  19. package/coreStorage/CoreSqlSchemaSetup.d.ts +18 -0
  20. package/coreStorage/CoreSqlSchemaSetup.js +35 -0
  21. package/coreStorage/CoreSqlSchemaSetup.js.map +1 -0
  22. package/coreStorage/SqlApiCoreStorageOperationsFactory.d.ts +15 -0
  23. package/coreStorage/SqlApiCoreStorageOperationsFactory.js +32 -0
  24. package/coreStorage/SqlApiCoreStorageOperationsFactory.js.map +1 -0
  25. package/coreStorage/feature.d.ts +13 -0
  26. package/coreStorage/feature.js +13 -0
  27. package/coreStorage/feature.js.map +1 -0
  28. package/coreStorage/index.d.ts +1 -0
  29. package/coreStorage/index.js +1 -0
  30. package/createApiCoreSql.d.ts +13 -1
  31. package/createApiCoreSql.js +8 -8
  32. package/createApiCoreSql.js.map +1 -1
  33. package/index.d.ts +16 -3
  34. package/index.js +10 -2
  35. package/index.js.map +1 -1
  36. package/keyValueStore/index.js +19 -17
  37. package/keyValueStore/index.js.map +1 -1
  38. package/package.json +8 -7
  39. package/schemaConfig/abstractions.d.ts +22 -0
  40. package/schemaConfig/abstractions.js +5 -0
  41. package/schemaConfig/abstractions.js.map +1 -0
  42. package/schemaConfig/index.d.ts +1 -0
  43. package/schemaConfig/index.js +1 -0
  44. package/schemaMemory/ensureTable.d.ts +28 -0
  45. package/schemaMemory/ensureTable.js +43 -0
  46. package/schemaMemory/ensureTable.js.map +1 -0
  47. package/schemaMemory/getConnectionKey.d.ts +8 -0
  48. package/schemaMemory/getConnectionKey.js +15 -0
  49. package/schemaMemory/getConnectionKey.js.map +1 -0
  50. package/schemaMemory/getSchemaMemory.d.ts +37 -0
  51. package/schemaMemory/getSchemaMemory.js +53 -0
  52. package/schemaMemory/getSchemaMemory.js.map +1 -0
  53. package/schemaSetup/abstractions.d.ts +67 -0
  54. package/schemaSetup/abstractions.js +6 -0
  55. package/schemaSetup/abstractions.js.map +1 -0
  56. package/schemaSetup/index.d.ts +4 -0
  57. package/schemaSetup/index.js +2 -0
  58. package/schemaSetup/runSchemaSetupSteps.d.ts +34 -0
  59. package/schemaSetup/runSchemaSetupSteps.js +35 -0
  60. package/schemaSetup/runSchemaSetupSteps.js.map +1 -0
  61. package/security/index.js +47 -47
  62. package/security/index.js.map +1 -1
  63. package/serviceDiscovery/SqlServiceManifestLoader.d.ts +1 -1
  64. package/serviceDiscovery/SqlServiceManifestLoader.js +3 -8
  65. package/serviceDiscovery/SqlServiceManifestLoader.js.map +1 -1
  66. package/serviceDiscovery/SqlServiceManifestWriter.d.ts +16 -0
  67. package/serviceDiscovery/SqlServiceManifestWriter.js +27 -0
  68. package/serviceDiscovery/SqlServiceManifestWriter.js.map +1 -0
  69. package/serviceDiscovery/index.d.ts +1 -0
  70. package/serviceDiscovery/index.js +1 -0
  71. package/serviceDiscovery/serviceManifestsTable.d.ts +13 -0
  72. package/serviceDiscovery/serviceManifestsTable.js +8 -0
  73. package/serviceDiscovery/serviceManifestsTable.js.map +1 -0
  74. package/storage/types.d.ts +22 -0
  75. package/storage/types.js +0 -0
  76. package/tenancy/index.js +9 -9
  77. package/tenancy/index.js.map +1 -1
  78. package/ApiCoreSqlFeature.d.ts +0 -18
  79. package/ApiCoreSqlFeature.js +0 -18
  80. package/ApiCoreSqlFeature.js.map +0 -1
@@ -0,0 +1,43 @@
1
+ const inFlight = new Map();
2
+ const transactionIds = new WeakMap();
3
+ let lastTransactionId = 0;
4
+ const handleOf = (knex)=>{
5
+ if (!knex.isTransaction) return "connection";
6
+ let id = transactionIds.get(knex);
7
+ if (void 0 === id) {
8
+ lastTransactionId += 1;
9
+ id = lastTransactionId;
10
+ transactionIds.set(knex, id);
11
+ }
12
+ return `trx${id}`;
13
+ };
14
+ function ensureTable(params) {
15
+ const { knex, memory, tableName, create } = params;
16
+ if (memory.known.has(tableName)) return Promise.resolve();
17
+ const generation = memory.generation;
18
+ const key = `${memory.key}#${generation}:${tableName}:${handleOf(knex)}`;
19
+ const pending = inFlight.get(key);
20
+ if (pending) return pending;
21
+ const check = createTableIfMissing(knex, tableName, create).then(()=>{
22
+ if (memory.generation === generation) recordTable(knex, memory, tableName);
23
+ }).finally(()=>{
24
+ if (inFlight.get(key) === check) inFlight.delete(key);
25
+ });
26
+ inFlight.set(key, check);
27
+ return check;
28
+ }
29
+ function recordTable(knex, memory, tableName) {
30
+ if (!knex.isTransaction) memory.known.add(tableName);
31
+ }
32
+ async function createTableIfMissing(knex, tableName, create) {
33
+ if (await knex.schema.hasTable(tableName)) return;
34
+ try {
35
+ await knex.schema.createTable(tableName, create);
36
+ } catch (error) {
37
+ if (await knex.schema.hasTable(tableName)) return;
38
+ throw error;
39
+ }
40
+ }
41
+ export { createTableIfMissing, ensureTable, recordTable };
42
+
43
+ //# sourceMappingURL=ensureTable.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schemaMemory/ensureTable.js","sources":["../../src/schemaMemory/ensureTable.ts"],"sourcesContent":["import type { Knex } from \"knex\";\nimport type { ISchemaMemory } from \"./getSchemaMemory.js\";\n\nexport type TableCreator = (table: Knex.CreateTableBuilder) => void;\n\nexport interface EnsureTableParams {\n /** The connection or transaction to check and create the table on. */\n knex: Knex;\n /** What the process knows about the tables this one belongs to. */\n memory: ISchemaMemory;\n tableName: string;\n create: TableCreator;\n}\n\n/*\n * Checks in flight, per memory, table and handle, so concurrent first uses share one\n * hasTable+createTable instead of racing into \"table already exists\".\n */\nconst inFlight = new Map<string, Promise<void>>();\n\nconst transactionIds = new WeakMap<object, number>();\nlet lastTransactionId = 0;\n\n/*\n * Which handle a check runs on. A transaction shares its connection's key (`getConnectionKey`), but\n * a table it creates is visible to others only once it commits, and is gone if it rolls back. So a\n * check in a transaction is shared only with checks in that same transaction.\n */\nconst handleOf = (knex: Knex): string => {\n if (!knex.isTransaction) {\n return \"connection\";\n }\n let id = transactionIds.get(knex);\n if (id === undefined) {\n lastTransactionId += 1;\n id = lastTransactionId;\n transactionIds.set(knex, id);\n }\n return `trx${id}`;\n};\n\n/**\n * Creates the table if it doesn't exist yet, once per process: a table the memory knows is skipped,\n * and concurrent callers on the same handle wait for one check. What a transaction creates is\n * remembered only by `recordTable` after it commits, never here, and nothing started before the\n * memory was reset is recorded after it.\n */\nexport function ensureTable(params: EnsureTableParams): Promise<void> {\n const { knex, memory, tableName, create } = params;\n if (memory.known.has(tableName)) {\n return Promise.resolve();\n }\n\n const generation = memory.generation;\n const key = `${memory.key}#${generation}:${tableName}:${handleOf(knex)}`;\n const pending = inFlight.get(key);\n if (pending) {\n return pending;\n }\n\n const check: Promise<void> = createTableIfMissing(knex, tableName, create)\n .then(() => {\n if (memory.generation === generation) {\n recordTable(knex, memory, tableName);\n }\n })\n .finally(() => {\n if (inFlight.get(key) === check) {\n inFlight.delete(key);\n }\n });\n inFlight.set(key, check);\n return check;\n}\n\n/**\n * Records that the table exists, unless `knex` is a transaction: it can still roll back, and the\n * table with it, so only a committed table is known.\n */\nexport function recordTable(knex: Knex, memory: ISchemaMemory, tableName: string): void {\n if (!knex.isTransaction) {\n memory.known.add(tableName);\n }\n}\n\n/**\n * Creates the table if it doesn't exist. Another process (or connection) may create it between the\n * check and the create: if it exists after a failed create, that's success.\n */\nexport async function createTableIfMissing(\n knex: Knex,\n tableName: string,\n create: TableCreator\n): Promise<void> {\n if (await knex.schema.hasTable(tableName)) {\n return;\n }\n try {\n await knex.schema.createTable(tableName, create);\n } catch (error) {\n if (await knex.schema.hasTable(tableName)) {\n return;\n }\n throw error;\n }\n}\n"],"names":["inFlight","Map","transactionIds","WeakMap","lastTransactionId","handleOf","knex","id","undefined","ensureTable","params","memory","tableName","create","Promise","generation","key","pending","check","createTableIfMissing","recordTable","error"],"mappings":"AAkBA,MAAMA,WAAW,IAAIC;AAErB,MAAMC,iBAAiB,IAAIC;AAC3B,IAAIC,oBAAoB;AAOxB,MAAMC,WAAW,CAACC;IACd,IAAI,CAACA,KAAK,aAAa,EACnB,OAAO;IAEX,IAAIC,KAAKL,eAAe,GAAG,CAACI;IAC5B,IAAIC,AAAOC,WAAPD,IAAkB;QAClBH,qBAAqB;QACrBG,KAAKH;QACLF,eAAe,GAAG,CAACI,MAAMC;IAC7B;IACA,OAAO,CAAC,GAAG,EAAEA,IAAI;AACrB;AAQO,SAASE,YAAYC,MAAyB;IACjD,MAAM,EAAEJ,IAAI,EAAEK,MAAM,EAAEC,SAAS,EAAEC,MAAM,EAAE,GAAGH;IAC5C,IAAIC,OAAO,KAAK,CAAC,GAAG,CAACC,YACjB,OAAOE,QAAQ,OAAO;IAG1B,MAAMC,aAAaJ,OAAO,UAAU;IACpC,MAAMK,MAAM,GAAGL,OAAO,GAAG,CAAC,CAAC,EAAEI,WAAW,CAAC,EAAEH,UAAU,CAAC,EAAEP,SAASC,OAAO;IACxE,MAAMW,UAAUjB,SAAS,GAAG,CAACgB;IAC7B,IAAIC,SACA,OAAOA;IAGX,MAAMC,QAAuBC,qBAAqBb,MAAMM,WAAWC,QAC9D,IAAI,CAAC;QACF,IAAIF,OAAO,UAAU,KAAKI,YACtBK,YAAYd,MAAMK,QAAQC;IAElC,GACC,OAAO,CAAC;QACL,IAAIZ,SAAS,GAAG,CAACgB,SAASE,OACtBlB,SAAS,MAAM,CAACgB;IAExB;IACJhB,SAAS,GAAG,CAACgB,KAAKE;IAClB,OAAOA;AACX;AAMO,SAASE,YAAYd,IAAU,EAAEK,MAAqB,EAAEC,SAAiB;IAC5E,IAAI,CAACN,KAAK,aAAa,EACnBK,OAAO,KAAK,CAAC,GAAG,CAACC;AAEzB;AAMO,eAAeO,qBAClBb,IAAU,EACVM,SAAiB,EACjBC,MAAoB;IAEpB,IAAI,MAAMP,KAAK,MAAM,CAAC,QAAQ,CAACM,YAC3B;IAEJ,IAAI;QACA,MAAMN,KAAK,MAAM,CAAC,WAAW,CAACM,WAAWC;IAC7C,EAAE,OAAOQ,OAAO;QACZ,IAAI,MAAMf,KAAK,MAAM,CAAC,QAAQ,CAACM,YAC3B;QAEJ,MAAMS;IACV;AACJ"}
@@ -0,0 +1,8 @@
1
+ import type { Knex } from "knex";
2
+ /**
3
+ * A short id for the database a Knex instance connects to, for keys of the process's schema memory
4
+ * (`getSchemaMemory`). A transaction shares its connection's config, so it gets its connection's id:
5
+ * what setup learns in a transaction is what the connection knows afterwards. Two Knex instances
6
+ * built separately get different ids, even for the same database.
7
+ */
8
+ export declare function getConnectionKey(knex: Knex): string;
@@ -0,0 +1,15 @@
1
+ const keys = new WeakMap();
2
+ let next = 0;
3
+ function getConnectionKey(knex) {
4
+ const identity = knex.client?.config ?? knex;
5
+ let key = keys.get(identity);
6
+ if (!key) {
7
+ next += 1;
8
+ key = `db${next}`;
9
+ keys.set(identity, key);
10
+ }
11
+ return key;
12
+ }
13
+ export { getConnectionKey };
14
+
15
+ //# sourceMappingURL=getConnectionKey.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schemaMemory/getConnectionKey.js","sources":["../../src/schemaMemory/getConnectionKey.ts"],"sourcesContent":["import type { Knex } from \"knex\";\n\nconst keys = new WeakMap<object, string>();\nlet next = 0;\n\n/**\n * A short id for the database a Knex instance connects to, for keys of the process's schema memory\n * (`getSchemaMemory`). A transaction shares its connection's config, so it gets its connection's id:\n * what setup learns in a transaction is what the connection knows afterwards. Two Knex instances\n * built separately get different ids, even for the same database.\n */\nexport function getConnectionKey(knex: Knex): string {\n const identity: object = knex.client?.config ?? knex;\n let key = keys.get(identity);\n if (!key) {\n next += 1;\n key = `db${next}`;\n keys.set(identity, key);\n }\n return key;\n}\n"],"names":["keys","WeakMap","next","getConnectionKey","knex","identity","key"],"mappings":"AAEA,MAAMA,OAAO,IAAIC;AACjB,IAAIC,OAAO;AAQJ,SAASC,iBAAiBC,IAAU;IACvC,MAAMC,WAAmBD,KAAK,MAAM,EAAE,UAAUA;IAChD,IAAIE,MAAMN,KAAK,GAAG,CAACK;IACnB,IAAI,CAACC,KAAK;QACNJ,QAAQ;QACRI,MAAM,CAAC,EAAE,EAAEJ,MAAM;QACjBF,KAAK,GAAG,CAACK,UAAUC;IACvB;IACA,OAAOA;AACX"}
@@ -0,0 +1,37 @@
1
+ /**
2
+ * What this process knows about some tables: whether they were created, and a set of names it has
3
+ * checked (tables, tenants). Shared by every caller that asks for the same key, so it outlives the
4
+ * instance that learned it. The Postgres CMS and folder catalog are registered per request (they
5
+ * come with the project's extensions), so each request builds new instances: what they learn about
6
+ * the tables must live here, for the process.
7
+ */
8
+ export interface ISchemaMemory {
9
+ /** What the memory is of: the key it was asked for with. */
10
+ readonly key: string;
11
+ /**
12
+ * Runs `create` once per process; callers at the same time wait for the same run. A failed run is
13
+ * forgotten, so the next call tries again.
14
+ */
15
+ once(create: () => Promise<void>): Promise<void>;
16
+ /** Whether the tables are known to exist (`once` succeeded, or `markReady` was called). */
17
+ isReady(): boolean;
18
+ /** Records that the tables exist (created in a caller's transaction that has committed). */
19
+ markReady(): void;
20
+ /** Names this process has checked (tables, tenants). */
21
+ readonly known: Set<string>;
22
+ /**
23
+ * Goes up on every `reset()`. Work that started before a reset must not record what it learned
24
+ * after it: compare the value taken at the start with the current one.
25
+ */
26
+ readonly generation: number;
27
+ /** Forgets everything (test setups drop all tables between tests). */
28
+ reset(): void;
29
+ }
30
+ /**
31
+ * The process's memory for `key` (a table name, or a name that stands for a set of tables). Made on
32
+ * first use, with `onReset` run whenever it is reset; later callers get the same one.
33
+ *
34
+ * Each memory joins `globalThis.__sqlTableManagers` once, so test setups that drop all tables and
35
+ * call `reset()` on every entry reset it too.
36
+ */
37
+ export declare function getSchemaMemory(key: string, onReset?: () => void): ISchemaMemory;
@@ -0,0 +1,53 @@
1
+ class SchemaMemory {
2
+ constructor(key, onReset){
3
+ this.key = key;
4
+ this.onReset = onReset;
5
+ this.known = new Set();
6
+ this.ready = false;
7
+ this.currentGeneration = 0;
8
+ }
9
+ once(create) {
10
+ if (this.ready) return Promise.resolve();
11
+ if (this.pending) return this.pending;
12
+ const generation = this.currentGeneration;
13
+ const run = create().then(()=>{
14
+ if (this.currentGeneration === generation) this.ready = true;
15
+ }, (error)=>{
16
+ if (this.pending === run) this.pending = void 0;
17
+ throw error;
18
+ });
19
+ this.pending = run;
20
+ return run;
21
+ }
22
+ get generation() {
23
+ return this.currentGeneration;
24
+ }
25
+ isReady() {
26
+ return this.ready;
27
+ }
28
+ markReady() {
29
+ this.ready = true;
30
+ }
31
+ reset() {
32
+ this.currentGeneration += 1;
33
+ this.pending = void 0;
34
+ this.ready = false;
35
+ this.known.clear();
36
+ this.onReset?.();
37
+ }
38
+ }
39
+ const memories = new Map();
40
+ function getSchemaMemory(key, onReset) {
41
+ let memory = memories.get(key);
42
+ if (!memory) {
43
+ memory = new SchemaMemory(key, onReset);
44
+ memories.set(key, memory);
45
+ const g = globalThis;
46
+ const managers = g.__sqlTableManagers ??= [];
47
+ managers.push(memory);
48
+ }
49
+ return memory;
50
+ }
51
+ export { getSchemaMemory };
52
+
53
+ //# sourceMappingURL=getSchemaMemory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schemaMemory/getSchemaMemory.js","sources":["../../src/schemaMemory/getSchemaMemory.ts"],"sourcesContent":["/**\n * What this process knows about some tables: whether they were created, and a set of names it has\n * checked (tables, tenants). Shared by every caller that asks for the same key, so it outlives the\n * instance that learned it. The Postgres CMS and folder catalog are registered per request (they\n * come with the project's extensions), so each request builds new instances: what they learn about\n * the tables must live here, for the process.\n */\nexport interface ISchemaMemory {\n /** What the memory is of: the key it was asked for with. */\n readonly key: string;\n /**\n * Runs `create` once per process; callers at the same time wait for the same run. A failed run is\n * forgotten, so the next call tries again.\n */\n once(create: () => Promise<void>): Promise<void>;\n /** Whether the tables are known to exist (`once` succeeded, or `markReady` was called). */\n isReady(): boolean;\n /** Records that the tables exist (created in a caller's transaction that has committed). */\n markReady(): void;\n /** Names this process has checked (tables, tenants). */\n readonly known: Set<string>;\n /**\n * Goes up on every `reset()`. Work that started before a reset must not record what it learned\n * after it: compare the value taken at the start with the current one.\n */\n readonly generation: number;\n /** Forgets everything (test setups drop all tables between tests). */\n reset(): void;\n}\n\nclass SchemaMemory implements ISchemaMemory {\n public readonly known = new Set<string>();\n private pending?: Promise<void>;\n private ready = false;\n private currentGeneration = 0;\n\n public constructor(\n public readonly key: string,\n private readonly onReset?: () => void\n ) {}\n\n public once(create: () => Promise<void>): Promise<void> {\n if (this.ready) {\n return Promise.resolve();\n }\n if (this.pending) {\n return this.pending;\n }\n // A run that ends after a reset() must neither mark the tables ready nor clear a newer run.\n const generation = this.currentGeneration;\n const run: Promise<void> = create().then(\n () => {\n if (this.currentGeneration === generation) {\n this.ready = true;\n }\n },\n error => {\n if (this.pending === run) {\n this.pending = undefined;\n }\n throw error;\n }\n );\n this.pending = run;\n return run;\n }\n\n public get generation(): number {\n return this.currentGeneration;\n }\n\n public isReady(): boolean {\n return this.ready;\n }\n\n public markReady(): void {\n this.ready = true;\n }\n\n public reset(): void {\n this.currentGeneration += 1;\n this.pending = undefined;\n this.ready = false;\n this.known.clear();\n this.onReset?.();\n }\n}\n\nconst memories = new Map<string, SchemaMemory>();\n\n/**\n * The process's memory for `key` (a table name, or a name that stands for a set of tables). Made on\n * first use, with `onReset` run whenever it is reset; later callers get the same one.\n *\n * Each memory joins `globalThis.__sqlTableManagers` once, so test setups that drop all tables and\n * call `reset()` on every entry reset it too.\n */\nexport function getSchemaMemory(key: string, onReset?: () => void): ISchemaMemory {\n let memory = memories.get(key);\n if (!memory) {\n memory = new SchemaMemory(key, onReset);\n memories.set(key, memory);\n const g = globalThis as Record<string, unknown>;\n const managers = (g.__sqlTableManagers ??= []) as ISchemaMemory[];\n managers.push(memory);\n }\n return memory;\n}\n"],"names":["SchemaMemory","key","onReset","Set","create","Promise","generation","run","error","undefined","memories","Map","getSchemaMemory","memory","g","globalThis","managers"],"mappings":"AA8BA,MAAMA;IAMF,YACoBC,GAAW,EACVC,OAAoB,CACvC;aAFkBD,GAAG,GAAHA;aACCC,OAAO,GAAPA;aAPL,KAAK,GAAG,IAAIC;aAEpB,KAAK,GAAG;aACR,iBAAiB,GAAG;IAKzB;IAEI,KAAKC,MAA2B,EAAiB;QACpD,IAAI,IAAI,CAAC,KAAK,EACV,OAAOC,QAAQ,OAAO;QAE1B,IAAI,IAAI,CAAC,OAAO,EACZ,OAAO,IAAI,CAAC,OAAO;QAGvB,MAAMC,aAAa,IAAI,CAAC,iBAAiB;QACzC,MAAMC,MAAqBH,SAAS,IAAI,CACpC;YACI,IAAI,IAAI,CAAC,iBAAiB,KAAKE,YAC3B,IAAI,CAAC,KAAK,GAAG;QAErB,GACAE,CAAAA;YACI,IAAI,IAAI,CAAC,OAAO,KAAKD,KACjB,IAAI,CAAC,OAAO,GAAGE;YAEnB,MAAMD;QACV;QAEJ,IAAI,CAAC,OAAO,GAAGD;QACf,OAAOA;IACX;IAEA,IAAW,aAAqB;QAC5B,OAAO,IAAI,CAAC,iBAAiB;IACjC;IAEO,UAAmB;QACtB,OAAO,IAAI,CAAC,KAAK;IACrB;IAEO,YAAkB;QACrB,IAAI,CAAC,KAAK,GAAG;IACjB;IAEO,QAAc;QACjB,IAAI,CAAC,iBAAiB,IAAI;QAC1B,IAAI,CAAC,OAAO,GAAGE;QACf,IAAI,CAAC,KAAK,GAAG;QACb,IAAI,CAAC,KAAK,CAAC,KAAK;QAChB,IAAI,CAAC,OAAO;IAChB;AACJ;AAEA,MAAMC,WAAW,IAAIC;AASd,SAASC,gBAAgBX,GAAW,EAAEC,OAAoB;IAC7D,IAAIW,SAASH,SAAS,GAAG,CAACT;IAC1B,IAAI,CAACY,QAAQ;QACTA,SAAS,IAAIb,aAAaC,KAAKC;QAC/BQ,SAAS,GAAG,CAACT,KAAKY;QAClB,MAAMC,IAAIC;QACV,MAAMC,WAAYF,EAAE,kBAAkB,KAAK,EAAE;QAC7CE,SAAS,IAAI,CAACH;IAClB;IACA,OAAOA;AACX"}
@@ -0,0 +1,67 @@
1
+ import type { Knex } from "knex";
2
+ import type { Container } from "@webiny/feature/api";
3
+ export interface ISqlSchemaSetup {
4
+ /**
5
+ * What the step sets up, as a short id (`core`, `websockets`, `cms`, `aco`). The runner reports
6
+ * the steps it ran by these names, and can check that a module it needs registered its step.
7
+ */
8
+ readonly name: string;
9
+ /**
10
+ * Brings the step's tables, indexes and functions up to date, whatever the schema-managed
11
+ * setting. Safe to run again: what already exists is kept. It never drops a table or a column,
12
+ * but a step may migrate in place. The Postgres CMS, for one, adds columns
13
+ * (`ALTER TABLE … ADD COLUMN IF NOT EXISTS`), changes column statistics, replaces its trigger
14
+ * functions, replaces the old count triggers and rebuilds the count rows from the search table
15
+ * once. The database user that runs setup needs the rights for that.
16
+ */
17
+ setup(): Promise<void>;
18
+ }
19
+ /**
20
+ * One step of the schema setup. Every part that owns tables registers its own step in a request's
21
+ * container: the storage's parts (core, audit logs, websockets), the transport's login storage, and
22
+ * the modules registered through the project's extensions (the Postgres CMS, the folder catalog).
23
+ * The setup runner runs every step it finds, so it doesn't need to know which modules exist.
24
+ */
25
+ export declare const SqlSchemaSetup: import("@webiny/di").Abstraction<ISqlSchemaSetup>;
26
+ export declare namespace SqlSchemaSetup {
27
+ type Interface = ISqlSchemaSetup;
28
+ }
29
+ /**
30
+ * What a request registers, as the transport builds every request's container: its storages (every
31
+ * `RequestStorage`), the API's features and the project's extensions. The schema setup builds its
32
+ * container with it, so it sets up exactly the tables the API uses, with their settings.
33
+ */
34
+ export interface ISqlSchemaSetupRequest {
35
+ register(container: Container): Promise<void>;
36
+ }
37
+ export interface SqlSchemaSetupRunParams {
38
+ /** Registers a request's parts in the setup's container. */
39
+ request: ISqlSchemaSetupRequest;
40
+ /**
41
+ * The connection to set the schema up on. Defaults to the storage's. The caller closes it.
42
+ * On Lambda, setup goes to the database's writer, not through the proxy the API uses.
43
+ */
44
+ knex?: Knex;
45
+ }
46
+ export interface ISqlSchemaSetupRunner {
47
+ /**
48
+ * Creates every table, index and function the API uses: opens the setup's transaction (on
49
+ * Postgres, behind an advisory lock), builds a container on it the way a request's is built,
50
+ * and runs every `SqlSchemaSetup` step in it. Keeps what exists, and is safe to run on every
51
+ * start or deploy (see `ISqlSchemaSetup.setup` for what a step may migrate). Afterwards the storage is schema-managed. Returns the names of the steps it
52
+ * ran.
53
+ */
54
+ run(params: SqlSchemaSetupRunParams): Promise<string[]>;
55
+ }
56
+ /**
57
+ * Runs the schema setup of the SQL storage. Each storage registers its implementation in the root:
58
+ * it knows how its engine runs DDL safely (a transaction behind an advisory lock on Postgres, a plain
59
+ * transaction on SQLite) and which modules it can't run without. The transport runs it before the
60
+ * API takes traffic: the standalone server at start, the Lambda API on its schema-setup event.
61
+ */
62
+ export declare const SqlSchemaSetupRunner: import("@webiny/di").Abstraction<ISqlSchemaSetupRunner>;
63
+ export declare namespace SqlSchemaSetupRunner {
64
+ type Interface = ISqlSchemaSetupRunner;
65
+ type Request = ISqlSchemaSetupRequest;
66
+ type RunParams = SqlSchemaSetupRunParams;
67
+ }
@@ -0,0 +1,6 @@
1
+ import { createAbstraction } from "@webiny/feature/api";
2
+ const SqlSchemaSetup = createAbstraction("Db/Sql/SchemaSetup");
3
+ const SqlSchemaSetupRunner = createAbstraction("Db/Sql/SchemaSetupRunner");
4
+ export { SqlSchemaSetup, SqlSchemaSetupRunner };
5
+
6
+ //# sourceMappingURL=abstractions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schemaSetup/abstractions.js","sources":["../../src/schemaSetup/abstractions.ts"],"sourcesContent":["import type { Knex } from \"knex\";\nimport type { Container } from \"@webiny/feature/api\";\nimport { createAbstraction } from \"@webiny/feature/api\";\n\nexport interface ISqlSchemaSetup {\n /**\n * What the step sets up, as a short id (`core`, `websockets`, `cms`, `aco`). The runner reports\n * the steps it ran by these names, and can check that a module it needs registered its step.\n */\n readonly name: string;\n /**\n * Brings the step's tables, indexes and functions up to date, whatever the schema-managed\n * setting. Safe to run again: what already exists is kept. It never drops a table or a column,\n * but a step may migrate in place. The Postgres CMS, for one, adds columns\n * (`ALTER TABLE … ADD COLUMN IF NOT EXISTS`), changes column statistics, replaces its trigger\n * functions, replaces the old count triggers and rebuilds the count rows from the search table\n * once. The database user that runs setup needs the rights for that.\n */\n setup(): Promise<void>;\n}\n\n/**\n * One step of the schema setup. Every part that owns tables registers its own step in a request's\n * container: the storage's parts (core, audit logs, websockets), the transport's login storage, and\n * the modules registered through the project's extensions (the Postgres CMS, the folder catalog).\n * The setup runner runs every step it finds, so it doesn't need to know which modules exist.\n */\nexport const SqlSchemaSetup = createAbstraction<ISqlSchemaSetup>(\"Db/Sql/SchemaSetup\");\n\nexport namespace SqlSchemaSetup {\n export type Interface = ISqlSchemaSetup;\n}\n\n/**\n * What a request registers, as the transport builds every request's container: its storages (every\n * `RequestStorage`), the API's features and the project's extensions. The schema setup builds its\n * container with it, so it sets up exactly the tables the API uses, with their settings.\n */\nexport interface ISqlSchemaSetupRequest {\n register(container: Container): Promise<void>;\n}\n\nexport interface SqlSchemaSetupRunParams {\n /** Registers a request's parts in the setup's container. */\n request: ISqlSchemaSetupRequest;\n /**\n * The connection to set the schema up on. Defaults to the storage's. The caller closes it.\n * On Lambda, setup goes to the database's writer, not through the proxy the API uses.\n */\n knex?: Knex;\n}\n\nexport interface ISqlSchemaSetupRunner {\n /**\n * Creates every table, index and function the API uses: opens the setup's transaction (on\n * Postgres, behind an advisory lock), builds a container on it the way a request's is built,\n * and runs every `SqlSchemaSetup` step in it. Keeps what exists, and is safe to run on every\n * start or deploy (see `ISqlSchemaSetup.setup` for what a step may migrate). Afterwards the storage is schema-managed. Returns the names of the steps it\n * ran.\n */\n run(params: SqlSchemaSetupRunParams): Promise<string[]>;\n}\n\n/**\n * Runs the schema setup of the SQL storage. Each storage registers its implementation in the root:\n * it knows how its engine runs DDL safely (a transaction behind an advisory lock on Postgres, a plain\n * transaction on SQLite) and which modules it can't run without. The transport runs it before the\n * API takes traffic: the standalone server at start, the Lambda API on its schema-setup event.\n */\nexport const SqlSchemaSetupRunner = createAbstraction<ISqlSchemaSetupRunner>(\n \"Db/Sql/SchemaSetupRunner\"\n);\n\nexport namespace SqlSchemaSetupRunner {\n export type Interface = ISqlSchemaSetupRunner;\n export type Request = ISqlSchemaSetupRequest;\n export type RunParams = SqlSchemaSetupRunParams;\n}\n"],"names":["SqlSchemaSetup","createAbstraction","SqlSchemaSetupRunner"],"mappings":";AA2BO,MAAMA,iBAAiBC,kBAAmC;AA0C1D,MAAMC,uBAAuBD,kBAChC"}
@@ -0,0 +1,4 @@
1
+ export { SqlSchemaSetup, SqlSchemaSetupRunner } from "./abstractions.js";
2
+ export type { ISqlSchemaSetupRequest, SqlSchemaSetupRunParams } from "./abstractions.js";
3
+ export { runSchemaSetupSteps } from "./runSchemaSetupSteps.js";
4
+ export type { RequiredSqlSchemaSetup, RunSchemaSetupStepsParams } from "./runSchemaSetupSteps.js";
@@ -0,0 +1,2 @@
1
+ export { SqlSchemaSetup, SqlSchemaSetupRunner } from "./abstractions.js";
2
+ export { runSchemaSetupSteps } from "./runSchemaSetupSteps.js";
@@ -0,0 +1,34 @@
1
+ import type { Knex } from "knex";
2
+ import type { Container } from "@webiny/feature/api";
3
+ import { type ISqlSchemaSetupRequest } from "./abstractions.js";
4
+ export interface RequiredSqlSchemaSetup {
5
+ /** The step's name (`SqlSchemaSetup.name`). */
6
+ name: string;
7
+ /** The error when no step of that name is registered: what to add to the project. */
8
+ message: string;
9
+ }
10
+ export interface RunSchemaSetupStepsParams {
11
+ /** The root container the storage is registered in. The setup's container is its child. */
12
+ root: Container;
13
+ /** The setup's connection: a transaction the runner opened. */
14
+ knex: Knex;
15
+ tableNamePrefix?: string;
16
+ /** Registers a request's parts in the setup's container. */
17
+ request: ISqlSchemaSetupRequest;
18
+ /** Steps the storage can't run without (a module the project must add). */
19
+ required?: RequiredSqlSchemaSetup[];
20
+ }
21
+ /**
22
+ * The part of schema setup every SQL storage shares, run inside the runner's transaction. It builds
23
+ * a container on the setup's connection the way a request's is built, and runs every schema setup
24
+ * step in it.
25
+ *
26
+ * The container is a child of the root, so it has what a request has (the logger, the storages'
27
+ * `RequestStorage`). The setup's connection is registered in it first, with schema-managed off:
28
+ * every storage the request registers runs on it, including the ones built while the request
29
+ * registers and the modules' singletons, which are built in the container that registers them.
30
+ *
31
+ * Checks `required` before running anything, so a missing module fails before any DDL. Returns the
32
+ * names of the steps it ran, in order.
33
+ */
34
+ export declare function runSchemaSetupSteps(params: RunSchemaSetupStepsParams): Promise<string[]>;
@@ -0,0 +1,35 @@
1
+ import { SqlConnectionFeature } from "../connection/SqlConnectionFeature.js";
2
+ import { SqlSchemaSetup } from "./abstractions.js";
3
+ async function runSchemaSetupSteps(params) {
4
+ const { root, knex, tableNamePrefix, request, required = [] } = params;
5
+ const container = root.createChildContainer();
6
+ SqlConnectionFeature.register(container, {
7
+ knex,
8
+ tableNamePrefix,
9
+ schemaManaged: false
10
+ });
11
+ await request.register(container);
12
+ const steps = resolveSteps(container, required);
13
+ for (const step of required)if (!steps.some((item)=>item.name === step.name)) throw new Error(step.message);
14
+ const done = [];
15
+ for (const step of steps){
16
+ await step.setup();
17
+ done.push(step.name);
18
+ }
19
+ return done;
20
+ }
21
+ function resolveSteps(container, required) {
22
+ try {
23
+ return container.resolveAll(SqlSchemaSetup);
24
+ } catch (error) {
25
+ if (!required.length) throw error;
26
+ const cause = error instanceof Error ? error.message : String(error);
27
+ const needs = required.map((step)=>step.message).join(" ");
28
+ throw new Error(`Schema setup could not build its steps (${cause}). ${needs}`, {
29
+ cause: error
30
+ });
31
+ }
32
+ }
33
+ export { runSchemaSetupSteps };
34
+
35
+ //# sourceMappingURL=runSchemaSetupSteps.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schemaSetup/runSchemaSetupSteps.js","sources":["../../src/schemaSetup/runSchemaSetupSteps.ts"],"sourcesContent":["import type { Knex } from \"knex\";\nimport type { Container } from \"@webiny/feature/api\";\nimport { SqlConnectionFeature } from \"~/connection/SqlConnectionFeature.js\";\nimport { SqlSchemaSetup, type ISqlSchemaSetupRequest } from \"./abstractions.js\";\n\nexport interface RequiredSqlSchemaSetup {\n /** The step's name (`SqlSchemaSetup.name`). */\n name: string;\n /** The error when no step of that name is registered: what to add to the project. */\n message: string;\n}\n\nexport interface RunSchemaSetupStepsParams {\n /** The root container the storage is registered in. The setup's container is its child. */\n root: Container;\n /** The setup's connection: a transaction the runner opened. */\n knex: Knex;\n tableNamePrefix?: string;\n /** Registers a request's parts in the setup's container. */\n request: ISqlSchemaSetupRequest;\n /** Steps the storage can't run without (a module the project must add). */\n required?: RequiredSqlSchemaSetup[];\n}\n\n/**\n * The part of schema setup every SQL storage shares, run inside the runner's transaction. It builds\n * a container on the setup's connection the way a request's is built, and runs every schema setup\n * step in it.\n *\n * The container is a child of the root, so it has what a request has (the logger, the storages'\n * `RequestStorage`). The setup's connection is registered in it first, with schema-managed off:\n * every storage the request registers runs on it, including the ones built while the request\n * registers and the modules' singletons, which are built in the container that registers them.\n *\n * Checks `required` before running anything, so a missing module fails before any DDL. Returns the\n * names of the steps it ran, in order.\n */\nexport async function runSchemaSetupSteps(params: RunSchemaSetupStepsParams): Promise<string[]> {\n const { root, knex, tableNamePrefix, request, required = [] } = params;\n\n const container = root.createChildContainer();\n SqlConnectionFeature.register(container, { knex, tableNamePrefix, schemaManaged: false });\n await request.register(container);\n\n const steps = resolveSteps(container, required);\n for (const step of required) {\n if (!steps.some(item => item.name === step.name)) {\n throw new Error(step.message);\n }\n }\n\n const done: string[] = [];\n for (const step of steps) {\n await step.setup();\n done.push(step.name);\n }\n return done;\n}\n\n/**\n * Builds the steps. A step whose module needs another one that is missing (the folder catalog needs\n * the CMS's table names) can't be built, and that fails before any step has a name to check. So\n * the failure says which modules the storage needs, with the cause.\n */\nfunction resolveSteps(container: Container, required: RequiredSqlSchemaSetup[]) {\n try {\n return container.resolveAll(SqlSchemaSetup);\n } catch (error) {\n if (!required.length) {\n throw error;\n }\n const cause = error instanceof Error ? error.message : String(error);\n const needs = required.map(step => step.message).join(\" \");\n throw new Error(`Schema setup could not build its steps (${cause}). ${needs}`, {\n cause: error\n });\n }\n}\n"],"names":["runSchemaSetupSteps","params","root","knex","tableNamePrefix","request","required","container","SqlConnectionFeature","steps","resolveSteps","step","item","Error","done","SqlSchemaSetup","error","cause","String","needs"],"mappings":";;AAqCO,eAAeA,oBAAoBC,MAAiC;IACvE,MAAM,EAAEC,IAAI,EAAEC,IAAI,EAAEC,eAAe,EAAEC,OAAO,EAAEC,WAAW,EAAE,EAAE,GAAGL;IAEhE,MAAMM,YAAYL,KAAK,oBAAoB;IAC3CM,qBAAqB,QAAQ,CAACD,WAAW;QAAEJ;QAAMC;QAAiB,eAAe;IAAM;IACvF,MAAMC,QAAQ,QAAQ,CAACE;IAEvB,MAAME,QAAQC,aAAaH,WAAWD;IACtC,KAAK,MAAMK,QAAQL,SACf,IAAI,CAACG,MAAM,IAAI,CAACG,CAAAA,OAAQA,KAAK,IAAI,KAAKD,KAAK,IAAI,GAC3C,MAAM,IAAIE,MAAMF,KAAK,OAAO;IAIpC,MAAMG,OAAiB,EAAE;IACzB,KAAK,MAAMH,QAAQF,MAAO;QACtB,MAAME,KAAK,KAAK;QAChBG,KAAK,IAAI,CAACH,KAAK,IAAI;IACvB;IACA,OAAOG;AACX;AAOA,SAASJ,aAAaH,SAAoB,EAAED,QAAkC;IAC1E,IAAI;QACA,OAAOC,UAAU,UAAU,CAACQ;IAChC,EAAE,OAAOC,OAAO;QACZ,IAAI,CAACV,SAAS,MAAM,EAChB,MAAMU;QAEV,MAAMC,QAAQD,iBAAiBH,QAAQG,MAAM,OAAO,GAAGE,OAAOF;QAC9D,MAAMG,QAAQb,SAAS,GAAG,CAACK,CAAAA,OAAQA,KAAK,OAAO,EAAE,IAAI,CAAC;QACtD,MAAM,IAAIE,MAAM,CAAC,wCAAwC,EAAEI,MAAM,GAAG,EAAEE,OAAO,EAAE;YAC3E,OAAOH;QACX;IACJ;AACJ"}
package/security/index.js CHANGED
@@ -5,53 +5,53 @@ const TEAMS_TABLE = "webiny_core_teams";
5
5
  const API_KEYS_TABLE = "webiny_core_api_keys";
6
6
  const createStorageOperations = (params)=>{
7
7
  const { knex, tableManager } = params;
8
- const ensureRolesTable = ()=>tableManager.ensure(ROLES_TABLE, (table)=>{
9
- table.text("id").notNullable();
10
- table.text("tenant").notNullable();
11
- table.text("slug").notNullable();
12
- table.text("data").notNullable();
13
- table.primary([
14
- "tenant",
15
- "id"
16
- ]);
17
- table.unique([
18
- "tenant",
19
- "slug"
20
- ]);
21
- });
22
- const ensureTeamsTable = ()=>tableManager.ensure(TEAMS_TABLE, (table)=>{
23
- table.text("id").notNullable();
24
- table.text("tenant").notNullable();
25
- table.text("slug").notNullable();
26
- table.text("data").notNullable();
27
- table.primary([
28
- "tenant",
29
- "id"
30
- ]);
31
- table.unique([
32
- "tenant",
33
- "slug"
34
- ]);
35
- });
36
- const ensureApiKeysTable = ()=>tableManager.ensure(API_KEYS_TABLE, (table)=>{
37
- table.text("id").notNullable();
38
- table.text("tenant").notNullable();
39
- table.text("token").notNullable();
40
- table.text("slug").notNullable();
41
- table.text("data").notNullable();
42
- table.primary([
43
- "tenant",
44
- "id"
45
- ]);
46
- table.unique([
47
- "tenant",
48
- "token"
49
- ]);
50
- table.unique([
51
- "tenant",
52
- "slug"
53
- ]);
54
- });
8
+ const ensureRolesTable = tableManager.define(ROLES_TABLE, (table)=>{
9
+ table.text("id").notNullable();
10
+ table.text("tenant").notNullable();
11
+ table.text("slug").notNullable();
12
+ table.text("data").notNullable();
13
+ table.primary([
14
+ "tenant",
15
+ "id"
16
+ ]);
17
+ table.unique([
18
+ "tenant",
19
+ "slug"
20
+ ]);
21
+ });
22
+ const ensureTeamsTable = tableManager.define(TEAMS_TABLE, (table)=>{
23
+ table.text("id").notNullable();
24
+ table.text("tenant").notNullable();
25
+ table.text("slug").notNullable();
26
+ table.text("data").notNullable();
27
+ table.primary([
28
+ "tenant",
29
+ "id"
30
+ ]);
31
+ table.unique([
32
+ "tenant",
33
+ "slug"
34
+ ]);
35
+ });
36
+ const ensureApiKeysTable = tableManager.define(API_KEYS_TABLE, (table)=>{
37
+ table.text("id").notNullable();
38
+ table.text("tenant").notNullable();
39
+ table.text("token").notNullable();
40
+ table.text("slug").notNullable();
41
+ table.text("data").notNullable();
42
+ table.primary([
43
+ "tenant",
44
+ "id"
45
+ ]);
46
+ table.unique([
47
+ "tenant",
48
+ "token"
49
+ ]);
50
+ table.unique([
51
+ "tenant",
52
+ "slug"
53
+ ]);
54
+ });
55
55
  const rolesQuery = ()=>knex(tableManager.resolve(ROLES_TABLE));
56
56
  const teamsQuery = ()=>knex(tableManager.resolve(TEAMS_TABLE));
57
57
  const apiKeysQuery = ()=>knex(tableManager.resolve(API_KEYS_TABLE));
@@ -1 +1 @@
1
- {"version":3,"file":"security/index.js","sources":["../../src/security/index.ts"],"sourcesContent":["import type { Knex } from \"knex\";\nimport type {\n SecurityStorageOperations,\n StorageApiKey,\n StorageRole,\n StorageTeam\n} from \"@webiny/api-core/types/security.js\";\nimport WebinyError from \"@webiny/error\";\nimport type { TableManager } from \"~/TableManager.js\";\nimport { sortItems } from \"~/sortItems.js\";\n\nconst ROLES_TABLE = \"webiny_core_roles\";\nconst TEAMS_TABLE = \"webiny_core_teams\";\nconst API_KEYS_TABLE = \"webiny_core_api_keys\";\n\ninterface IRoleRow {\n id: string;\n tenant: string;\n slug: string;\n data: string;\n}\n\ninterface ITeamRow {\n id: string;\n tenant: string;\n slug: string;\n data: string;\n}\n\ninterface IApiKeyRow {\n id: string;\n tenant: string;\n token: string;\n slug: string;\n data: string;\n}\n\ninterface CreateStorageOperationsParams {\n knex: Knex;\n tableManager: TableManager;\n}\n\nexport const createStorageOperations = (\n params: CreateStorageOperationsParams\n): SecurityStorageOperations => {\n const { knex, tableManager } = params;\n\n const ensureRolesTable = () => {\n return tableManager.ensure(ROLES_TABLE, table => {\n table.text(\"id\").notNullable();\n table.text(\"tenant\").notNullable();\n table.text(\"slug\").notNullable();\n table.text(\"data\").notNullable();\n\n table.primary([\"tenant\", \"id\"]);\n table.unique([\"tenant\", \"slug\"]);\n });\n };\n\n const ensureTeamsTable = () => {\n return tableManager.ensure(TEAMS_TABLE, table => {\n table.text(\"id\").notNullable();\n table.text(\"tenant\").notNullable();\n table.text(\"slug\").notNullable();\n table.text(\"data\").notNullable();\n\n table.primary([\"tenant\", \"id\"]);\n table.unique([\"tenant\", \"slug\"]);\n });\n };\n\n const ensureApiKeysTable = () => {\n return tableManager.ensure(API_KEYS_TABLE, table => {\n table.text(\"id\").notNullable();\n table.text(\"tenant\").notNullable();\n table.text(\"token\").notNullable();\n table.text(\"slug\").notNullable();\n table.text(\"data\").notNullable();\n\n table.primary([\"tenant\", \"id\"]);\n table.unique([\"tenant\", \"token\"]);\n table.unique([\"tenant\", \"slug\"]);\n });\n };\n\n const rolesQuery = () => knex<IRoleRow>(tableManager.resolve(ROLES_TABLE));\n const teamsQuery = () => knex<ITeamRow>(tableManager.resolve(TEAMS_TABLE));\n const apiKeysQuery = () => knex<IApiKeyRow>(tableManager.resolve(API_KEYS_TABLE));\n\n return {\n /* Roles */\n async getRole({ where: { tenant, id, slug } }) {\n await ensureRolesTable();\n\n try {\n if (id) {\n const row = await rolesQuery()\n .where(\"tenant\", tenant)\n .andWhere(\"id\", id)\n .first();\n\n return row ? (JSON.parse(row.data) as StorageRole) : null;\n }\n\n const row = await rolesQuery()\n .where(\"tenant\", tenant)\n .andWhere(\"slug\", slug as string)\n .first();\n\n return row ? (JSON.parse(row.data) as StorageRole) : null;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load role.\",\n code: \"GET_ROLE_ERROR\",\n data: { id, slug }\n });\n }\n },\n\n async listRoles({ where: { tenant, id_in, slug_in }, sort }) {\n await ensureRolesTable();\n\n try {\n const qb = rolesQuery().where(\"tenant\", tenant);\n\n if (Array.isArray(id_in)) {\n qb.whereIn(\"id\", id_in);\n } else if (Array.isArray(slug_in)) {\n qb.whereIn(\"slug\", slug_in);\n }\n\n const rows = await qb;\n const items = rows.map(row => JSON.parse(row.data) as StorageRole);\n\n return sortItems(items, sort);\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not list roles.\",\n code: \"LIST_ROLE_ERROR\"\n });\n }\n },\n\n async createRole({ role }) {\n await ensureRolesTable();\n\n try {\n await rolesQuery().insert({\n id: role.id,\n tenant: role.tenant,\n slug: role.slug,\n data: JSON.stringify(role)\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not create role.\",\n code: \"CREATE_ROLE_ERROR\",\n data: { role }\n });\n }\n },\n\n async updateRole({ role }) {\n await ensureRolesTable();\n\n try {\n await rolesQuery()\n .where(\"tenant\", role.tenant)\n .andWhere(\"id\", role.id)\n .update({\n slug: role.slug,\n data: JSON.stringify(role)\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not update role.\",\n code: \"UPDATE_ROLE_ERROR\",\n data: { role }\n });\n }\n },\n\n async deleteRole({ role }) {\n await ensureRolesTable();\n\n try {\n await rolesQuery().where(\"tenant\", role.tenant).andWhere(\"id\", role.id).delete();\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not delete role.\",\n code: \"DELETE_ROLE_ERROR\",\n data: { role }\n });\n }\n },\n\n /* Teams */\n async getTeam({ where: { tenant, id, slug } }) {\n await ensureTeamsTable();\n\n try {\n if (id) {\n const row = await teamsQuery()\n .where(\"tenant\", tenant)\n .andWhere(\"id\", id)\n .first();\n\n return row ? (JSON.parse(row.data) as StorageTeam) : null;\n }\n\n const row = await teamsQuery()\n .where(\"tenant\", tenant)\n .andWhere(\"slug\", slug as string)\n .first();\n\n return row ? (JSON.parse(row.data) as StorageTeam) : null;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load team.\",\n code: \"GET_TEAM_ERROR\",\n data: { id, slug }\n });\n }\n },\n\n async listTeams({ where: { tenant, id_in, slug_in }, sort }) {\n await ensureTeamsTable();\n\n try {\n const qb = teamsQuery().where(\"tenant\", tenant);\n\n if (Array.isArray(id_in)) {\n qb.whereIn(\"id\", id_in);\n } else if (Array.isArray(slug_in)) {\n qb.whereIn(\"slug\", slug_in);\n }\n\n const rows = await qb;\n const items = rows.map(row => JSON.parse(row.data) as StorageTeam);\n\n return sortItems(items, sort);\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not list teams.\",\n code: \"LIST_TEAM_ERROR\"\n });\n }\n },\n\n async createTeam({ team }) {\n await ensureTeamsTable();\n\n try {\n await teamsQuery().insert({\n id: team.id,\n tenant: team.tenant,\n slug: team.slug,\n data: JSON.stringify(team)\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not create team.\",\n code: \"CREATE_TEAM_ERROR\",\n data: { team }\n });\n }\n },\n\n async updateTeam({ team }) {\n await ensureTeamsTable();\n\n try {\n await teamsQuery()\n .where(\"tenant\", team.tenant)\n .andWhere(\"id\", team.id)\n .update({\n slug: team.slug,\n data: JSON.stringify(team)\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not update team.\",\n code: \"UPDATE_TEAM_ERROR\",\n data: { team }\n });\n }\n },\n\n async deleteTeam({ team }) {\n await ensureTeamsTable();\n\n try {\n await teamsQuery().where(\"tenant\", team.tenant).andWhere(\"id\", team.id).delete();\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not delete team.\",\n code: \"DELETE_TEAM_ERROR\",\n data: { team }\n });\n }\n },\n\n /* API Keys */\n async getApiKey({ id, tenant }) {\n await ensureApiKeysTable();\n\n try {\n const row = await apiKeysQuery().where(\"tenant\", tenant).andWhere(\"id\", id).first();\n\n return row ? (JSON.parse(row.data) as StorageApiKey) : null;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load api key.\",\n code: \"GET_API_KEY_ERROR\",\n data: { id }\n });\n }\n },\n\n async getApiKeyByToken({ tenant, token }) {\n await ensureApiKeysTable();\n\n try {\n const row = await apiKeysQuery()\n .where(\"tenant\", tenant)\n .andWhere(\"token\", token)\n .first();\n\n return row ? (JSON.parse(row.data) as StorageApiKey) : null;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load api key by token.\",\n code: \"GET_BY_TOKEN_API_KEY_ERROR\",\n data: { token }\n });\n }\n },\n\n async getApiKeyBySlug({ tenant, slug }) {\n await ensureApiKeysTable();\n\n try {\n const row = await apiKeysQuery()\n .where(\"tenant\", tenant)\n .andWhere(\"slug\", slug)\n .first();\n\n return row ? (JSON.parse(row.data) as StorageApiKey) : null;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load api key by slug.\",\n code: \"GET_BY_SLUG_API_KEY_ERROR\",\n data: { slug }\n });\n }\n },\n\n async listApiKeys({ where: { tenant }, sort }) {\n await ensureApiKeysTable();\n\n try {\n const rows = await apiKeysQuery().where(\"tenant\", tenant);\n const items = rows.map(row => JSON.parse(row.data) as StorageApiKey);\n\n return sortItems(items, sort);\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not list api keys.\",\n code: \"LIST_API_KEY_ERROR\"\n });\n }\n },\n\n async createApiKey({ apiKey }) {\n await ensureApiKeysTable();\n\n try {\n await apiKeysQuery().insert({\n id: apiKey.id,\n tenant: apiKey.tenant,\n token: apiKey.token,\n slug: apiKey.slug,\n data: JSON.stringify(apiKey)\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not create api key.\",\n code: \"CREATE_API_KEY_ERROR\",\n data: { apiKey }\n });\n }\n },\n\n async updateApiKey({ apiKey }) {\n await ensureApiKeysTable();\n\n try {\n await apiKeysQuery()\n .where(\"tenant\", apiKey.tenant)\n .andWhere(\"id\", apiKey.id)\n .update({\n token: apiKey.token,\n slug: apiKey.slug,\n data: JSON.stringify(apiKey)\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not update api key.\",\n code: \"UPDATE_API_KEY_ERROR\",\n data: { apiKey }\n });\n }\n },\n\n async deleteApiKey({ apiKey }) {\n await ensureApiKeysTable();\n\n try {\n await apiKeysQuery()\n .where(\"tenant\", apiKey.tenant)\n .andWhere(\"id\", apiKey.id)\n .delete();\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not delete api key.\",\n code: \"DELETE_API_KEY_ERROR\",\n data: { apiKey }\n });\n }\n }\n };\n};\n"],"names":["ROLES_TABLE","TEAMS_TABLE","API_KEYS_TABLE","createStorageOperations","params","knex","tableManager","ensureRolesTable","table","ensureTeamsTable","ensureApiKeysTable","rolesQuery","teamsQuery","apiKeysQuery","tenant","id","slug","row","JSON","err","WebinyError","id_in","slug_in","sort","qb","Array","rows","items","sortItems","role","team","token","apiKey"],"mappings":";;AAWA,MAAMA,cAAc;AACpB,MAAMC,cAAc;AACpB,MAAMC,iBAAiB;AA6BhB,MAAMC,0BAA0B,CACnCC;IAEA,MAAM,EAAEC,IAAI,EAAEC,YAAY,EAAE,GAAGF;IAE/B,MAAMG,mBAAmB,IACdD,aAAa,MAAM,CAACN,aAAaQ,CAAAA;YACpCA,MAAM,IAAI,CAAC,MAAM,WAAW;YAC5BA,MAAM,IAAI,CAAC,UAAU,WAAW;YAChCA,MAAM,IAAI,CAAC,QAAQ,WAAW;YAC9BA,MAAM,IAAI,CAAC,QAAQ,W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MAAMd,KAAK,SAAS,CAACc;gBACzB;YACR,EAAE,OAAOb,KAAK;gBACV,MAAMC,MAAAA,IAAgB,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;oBACN,MAAM;wBAAEa;oBAAO;gBACnB;YACJ;QACJ;QAEA,MAAM,cAAa,EAAEA,MAAM,EAAE;YACzB,MAAMtB;YAEN,IAAI;gBACA,MAAMG,eACD,KAAK,CAAC,UAAUmB,OAAO,MAAM,EAC7B,QAAQ,CAAC,MAAMA,OAAO,EAAE,EACxB,MAAM;YACf,EAAE,OAAOb,KAAK;gBACV,MAAMC,MAAAA,IAAgB,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;oBACN,MAAM;wBAAEa;oBAAO;gBACnB;YACJ;QACJ;IACJ;AACJ"}
1
+ {"version":3,"file":"security/index.js","sources":["../../src/security/index.ts"],"sourcesContent":["import type { Knex } from \"knex\";\nimport type {\n SecurityStorageOperations,\n StorageApiKey,\n StorageRole,\n StorageTeam\n} from \"@webiny/api-core/types/security.js\";\nimport WebinyError from \"@webiny/error\";\nimport type { TableManager } from \"~/TableManager.js\";\nimport { sortItems } from \"~/sortItems.js\";\n\nconst ROLES_TABLE = \"webiny_core_roles\";\nconst TEAMS_TABLE = \"webiny_core_teams\";\nconst API_KEYS_TABLE = \"webiny_core_api_keys\";\n\ninterface IRoleRow {\n id: string;\n tenant: string;\n slug: string;\n data: string;\n}\n\ninterface ITeamRow {\n id: string;\n tenant: string;\n slug: string;\n data: string;\n}\n\ninterface IApiKeyRow {\n id: string;\n tenant: string;\n token: string;\n slug: string;\n data: string;\n}\n\ninterface CreateStorageOperationsParams {\n knex: Knex;\n tableManager: TableManager;\n}\n\nexport const createStorageOperations = (\n params: CreateStorageOperationsParams\n): SecurityStorageOperations => {\n const { knex, tableManager } = params;\n\n const ensureRolesTable = tableManager.define(ROLES_TABLE, table => {\n table.text(\"id\").notNullable();\n table.text(\"tenant\").notNullable();\n table.text(\"slug\").notNullable();\n table.text(\"data\").notNullable();\n\n table.primary([\"tenant\", \"id\"]);\n table.unique([\"tenant\", \"slug\"]);\n });\n\n const ensureTeamsTable = tableManager.define(TEAMS_TABLE, table => {\n table.text(\"id\").notNullable();\n table.text(\"tenant\").notNullable();\n table.text(\"slug\").notNullable();\n table.text(\"data\").notNullable();\n\n table.primary([\"tenant\", \"id\"]);\n table.unique([\"tenant\", \"slug\"]);\n });\n\n const ensureApiKeysTable = tableManager.define(API_KEYS_TABLE, table => {\n table.text(\"id\").notNullable();\n table.text(\"tenant\").notNullable();\n table.text(\"token\").notNullable();\n table.text(\"slug\").notNullable();\n table.text(\"data\").notNullable();\n\n table.primary([\"tenant\", \"id\"]);\n table.unique([\"tenant\", \"token\"]);\n table.unique([\"tenant\", \"slug\"]);\n });\n\n const rolesQuery = () => knex<IRoleRow>(tableManager.resolve(ROLES_TABLE));\n const teamsQuery = () => knex<ITeamRow>(tableManager.resolve(TEAMS_TABLE));\n const apiKeysQuery = () => knex<IApiKeyRow>(tableManager.resolve(API_KEYS_TABLE));\n\n return {\n /* Roles */\n async getRole({ where: { tenant, id, slug } }) {\n await ensureRolesTable();\n\n try {\n if (id) {\n const row = await rolesQuery()\n .where(\"tenant\", tenant)\n .andWhere(\"id\", id)\n .first();\n\n return row ? (JSON.parse(row.data) as StorageRole) : null;\n }\n\n const row = await rolesQuery()\n .where(\"tenant\", tenant)\n .andWhere(\"slug\", slug as string)\n .first();\n\n return row ? (JSON.parse(row.data) as StorageRole) : null;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load role.\",\n code: \"GET_ROLE_ERROR\",\n data: { id, slug }\n });\n }\n },\n\n async listRoles({ where: { tenant, id_in, slug_in }, sort }) {\n await ensureRolesTable();\n\n try {\n const qb = rolesQuery().where(\"tenant\", tenant);\n\n if (Array.isArray(id_in)) {\n qb.whereIn(\"id\", id_in);\n } else if (Array.isArray(slug_in)) {\n qb.whereIn(\"slug\", slug_in);\n }\n\n const rows = await qb;\n const items = rows.map(row => JSON.parse(row.data) as StorageRole);\n\n return sortItems(items, sort);\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not list roles.\",\n code: \"LIST_ROLE_ERROR\"\n });\n }\n },\n\n async createRole({ role }) {\n await ensureRolesTable();\n\n try {\n await rolesQuery().insert({\n id: role.id,\n tenant: role.tenant,\n slug: role.slug,\n data: JSON.stringify(role)\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not create role.\",\n code: \"CREATE_ROLE_ERROR\",\n data: { role }\n });\n }\n },\n\n async updateRole({ role }) {\n await ensureRolesTable();\n\n try {\n await rolesQuery()\n .where(\"tenant\", role.tenant)\n .andWhere(\"id\", role.id)\n .update({\n slug: role.slug,\n data: JSON.stringify(role)\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not update role.\",\n code: \"UPDATE_ROLE_ERROR\",\n data: { role }\n });\n }\n },\n\n async deleteRole({ role }) {\n await ensureRolesTable();\n\n try {\n await rolesQuery().where(\"tenant\", role.tenant).andWhere(\"id\", role.id).delete();\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not delete role.\",\n code: \"DELETE_ROLE_ERROR\",\n data: { role }\n });\n }\n },\n\n /* Teams */\n async getTeam({ where: { tenant, id, slug } }) {\n await ensureTeamsTable();\n\n try {\n if (id) {\n const row = await teamsQuery()\n .where(\"tenant\", tenant)\n .andWhere(\"id\", id)\n .first();\n\n return row ? (JSON.parse(row.data) as StorageTeam) : null;\n }\n\n const row = await teamsQuery()\n .where(\"tenant\", tenant)\n .andWhere(\"slug\", slug as string)\n .first();\n\n return row ? (JSON.parse(row.data) as StorageTeam) : null;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load team.\",\n code: \"GET_TEAM_ERROR\",\n data: { id, slug }\n });\n }\n },\n\n async listTeams({ where: { tenant, id_in, slug_in }, sort }) {\n await ensureTeamsTable();\n\n try {\n const qb = teamsQuery().where(\"tenant\", tenant);\n\n if (Array.isArray(id_in)) {\n qb.whereIn(\"id\", id_in);\n } else if (Array.isArray(slug_in)) {\n qb.whereIn(\"slug\", slug_in);\n }\n\n const rows = await qb;\n const items = rows.map(row => JSON.parse(row.data) as StorageTeam);\n\n return sortItems(items, sort);\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not list teams.\",\n code: \"LIST_TEAM_ERROR\"\n });\n }\n },\n\n async createTeam({ team }) {\n await ensureTeamsTable();\n\n try {\n await teamsQuery().insert({\n id: team.id,\n tenant: team.tenant,\n slug: team.slug,\n data: JSON.stringify(team)\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not create team.\",\n code: \"CREATE_TEAM_ERROR\",\n data: { team }\n });\n }\n },\n\n async updateTeam({ team }) {\n await ensureTeamsTable();\n\n try {\n await teamsQuery()\n .where(\"tenant\", team.tenant)\n .andWhere(\"id\", team.id)\n .update({\n slug: team.slug,\n data: JSON.stringify(team)\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not update team.\",\n code: \"UPDATE_TEAM_ERROR\",\n data: { team }\n });\n }\n },\n\n async deleteTeam({ team }) {\n await ensureTeamsTable();\n\n try {\n await teamsQuery().where(\"tenant\", team.tenant).andWhere(\"id\", team.id).delete();\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not delete team.\",\n code: \"DELETE_TEAM_ERROR\",\n data: { team }\n });\n }\n },\n\n /* API Keys */\n async getApiKey({ id, tenant }) {\n await ensureApiKeysTable();\n\n try {\n const row = await apiKeysQuery().where(\"tenant\", tenant).andWhere(\"id\", id).first();\n\n return row ? (JSON.parse(row.data) as StorageApiKey) : null;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load api key.\",\n code: \"GET_API_KEY_ERROR\",\n data: { id }\n });\n }\n },\n\n async getApiKeyByToken({ tenant, token }) {\n await ensureApiKeysTable();\n\n try {\n const row = await apiKeysQuery()\n .where(\"tenant\", tenant)\n .andWhere(\"token\", token)\n .first();\n\n return row ? (JSON.parse(row.data) as StorageApiKey) : null;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load api key by token.\",\n code: \"GET_BY_TOKEN_API_KEY_ERROR\",\n data: { token }\n });\n }\n },\n\n async getApiKeyBySlug({ tenant, slug }) {\n await ensureApiKeysTable();\n\n try {\n const row = await apiKeysQuery()\n .where(\"tenant\", tenant)\n .andWhere(\"slug\", slug)\n .first();\n\n return row ? (JSON.parse(row.data) as StorageApiKey) : null;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load api key by slug.\",\n code: \"GET_BY_SLUG_API_KEY_ERROR\",\n data: { slug }\n });\n }\n },\n\n async listApiKeys({ where: { tenant }, sort }) {\n await ensureApiKeysTable();\n\n try {\n const rows = await apiKeysQuery().where(\"tenant\", tenant);\n const items = rows.map(row => JSON.parse(row.data) as StorageApiKey);\n\n return sortItems(items, sort);\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not list api keys.\",\n code: \"LIST_API_KEY_ERROR\"\n });\n }\n },\n\n async createApiKey({ apiKey }) {\n await ensureApiKeysTable();\n\n try {\n await apiKeysQuery().insert({\n id: apiKey.id,\n tenant: apiKey.tenant,\n token: apiKey.token,\n slug: apiKey.slug,\n data: JSON.stringify(apiKey)\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not create api key.\",\n code: \"CREATE_API_KEY_ERROR\",\n data: { apiKey }\n });\n }\n },\n\n async updateApiKey({ apiKey }) {\n await ensureApiKeysTable();\n\n try {\n await apiKeysQuery()\n .where(\"tenant\", apiKey.tenant)\n .andWhere(\"id\", apiKey.id)\n .update({\n token: apiKey.token,\n slug: apiKey.slug,\n data: JSON.stringify(apiKey)\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not update api key.\",\n code: \"UPDATE_API_KEY_ERROR\",\n data: { apiKey }\n });\n }\n },\n\n async deleteApiKey({ apiKey }) {\n await ensureApiKeysTable();\n\n try {\n await apiKeysQuery()\n .where(\"tenant\", apiKey.tenant)\n .andWhere(\"id\", apiKey.id)\n .delete();\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not delete api key.\",\n code: \"DELETE_API_KEY_ERROR\",\n data: { apiKey }\n });\n }\n }\n };\n};\n"],"names":["ROLES_TABLE","TEAMS_TABLE","API_KEYS_TABLE","createStorageOperations","params","knex","tableManager","ensureRolesTable","table","ensureTeamsTable","ensureApiKeysTable","rolesQuery","teamsQuery","apiKeysQuery","tenant","id","slug","row","JSON","err","WebinyError","id_in","slug_in","sort","qb","Array","rows","items","sortItems","role","team","token","apiKey"],"mappings":";;AAWA,MAAMA,cAAc;AACpB,MAAMC,cAAc;AACpB,MAAMC,iBAAiB;AA6BhB,MAAMC,0BAA0B,CACnCC;IAEA,MAAM,EAAEC,IAAI,EAAEC,YAAY,EAAE,GAAGF;IAE/B,MAAMG,mBAAmBD,aAAa,MAAM,CAACN,aAAaQ,CAAAA;QACtDA,MAAM,IAAI,CAAC,MAAM,WAAW;QAC5BA,MAAM,IAAI,CAAC,UAAU,WAAW;QAChCA,MAAM,IAAI,CAAC,QAAQ,WAAW;QAC9BA,MAAM,IAAI,CAAC,QAAQ,WAAW;QAE9BA,MAAM,OAAO,CAAC;YAAC;YAAU;SAAK;QAC9BA,MAAM,MAAM,CAAC;YAAC;YAAU;SAAO;IACnC;IAEA,MAAMC,mBAAmBH,aAAa,MAAM,CAACL,aAAaO,CAAAA;QACtDA,MAAM,IAAI,CAAC,MAAM,WAAW;QAC5BA,MAAM,IAAI,CAAC,UAAU,WAAW;QAChCA,MAAM,IAAI,CAAC,QAAQ,WAAW;QAC9BA,MAAM,IAAI,CAAC,QAAQ,WAAW;QAE9BA,MAAM,OAAO,CAAC;YAAC;YAAU;SAAK;QAC9BA,MAAM,MAAM,CAAC;YAAC;YAAU;SAAO;IACnC;IAEA,MAAME,qBAAqBJ,aAAa,MAAM,CAACJ,gBAAgBM,CAAAA;QAC3DA,MAAM,IAAI,CAAC,MAAM,WAAW;QAC5BA,MAAM,IAAI,CAAC,UAAU,WAAW;QAChCA,MAAM,IAAI,CAAC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BACT,MAAM;gBACV;YACJ;QACJ;QAEA,MAAM,cAAa,EAAEa,MAAM,EAAE;YACzB,MAAMtB;YAEN,IAAI;gBACA,MAAMG,eAAe,MAAM,CAAC;oBACxB,IAAImB,OAAO,EAAE;oBACb,QAAQA,OAAO,MAAM;oBACrB,OAAOA,OAAO,KAAK;oBACnB,MAAMA,OAAO,IAAI;oBACjB,MAAMd,KAAK,SAAS,CAACc;gBACzB;YACJ,EAAE,OAAOb,KAAK;gBACV,MAAMC,MAAAA,IAAgB,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;oBACN,MAAM;wBAAEa;oBAAO;gBACnB;YACJ;QACJ;QAEA,MAAM,cAAa,EAAEA,MAAM,EAAE;YACzB,MAAMtB;YAEN,IAAI;gBACA,MAAMG,eACD,KAAK,CAAC,UAAUmB,OAAO,MAAM,EAC7B,QAAQ,CAAC,MAAMA,OAAO,EAAE,EACxB,MAAM,CAAC;oBACJ,OAAOA,OAAO,KAAK;oBACnB,MAAMA,OAAO,IAAI;oBACjB,MAAMd,KAAK,SAAS,CAACc;gBACzB;YACR,EAAE,OAAOb,KAAK;gBACV,MAAMC,MAAAA,IAAgB,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;oBACN,MAAM;wBAAEa;oBAAO;gBACnB;YACJ;QACJ;QAEA,MAAM,cAAa,EAAEA,MAAM,EAAE;YACzB,MAAMtB;YAEN,IAAI;gBACA,MAAMG,eACD,KAAK,CAAC,UAAUmB,OAAO,MAAM,EAC7B,QAAQ,CAAC,MAAMA,OAAO,EAAE,EACxB,MAAM;YACf,EAAE,OAAOb,KAAK;gBACV,MAAMC,MAAAA,IAAgB,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;oBACN,MAAM;wBAAEa;oBAAO;gBACnB;YACJ;QACJ;IACJ;AACJ"}
@@ -4,10 +4,10 @@ import type { TableManager } from "../TableManager.js";
4
4
  export declare class SqlServiceManifestLoader implements IServiceManifestLoader {
5
5
  private readonly knex;
6
6
  private readonly tableManager;
7
+ private readonly ensureTable;
7
8
  constructor(knex: Knex, tableManager: TableManager);
8
9
  load(): Promise<{
9
10
  name: string;
10
11
  manifest: any;
11
12
  }[] | undefined>;
12
- private ensureTable;
13
13
  }
@@ -1,24 +1,19 @@
1
- const TABLE_NAME = "webiny_service_manifests";
1
+ import { SERVICE_MANIFESTS_TABLE, defineServiceManifestsTable } from "./serviceManifestsTable.js";
2
2
  class SqlServiceManifestLoader {
3
3
  constructor(knex, tableManager){
4
4
  this.knex = knex;
5
5
  this.tableManager = tableManager;
6
+ this.ensureTable = defineServiceManifestsTable(tableManager);
6
7
  }
7
8
  async load() {
8
9
  await this.ensureTable();
9
- const rows = await this.knex(this.tableManager.resolve(TABLE_NAME)).select("name", "manifest");
10
+ const rows = await this.knex(this.tableManager.resolve(SERVICE_MANIFESTS_TABLE)).select("name", "manifest");
10
11
  if (!rows.length) return;
11
12
  return rows.map((row)=>({
12
13
  name: row.name,
13
14
  manifest: JSON.parse(row.manifest)
14
15
  }));
15
16
  }
16
- async ensureTable() {
17
- await this.tableManager.ensure(TABLE_NAME, (table)=>{
18
- table.text("name").primary().notNullable();
19
- table.text("manifest").notNullable();
20
- });
21
- }
22
17
  }
23
18
  export { SqlServiceManifestLoader };
24
19