@yolean/evidence-sdk 0.0.0-stage → 4.1.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 (186) hide show
  1. package/CHANGELOG.md +538 -0
  2. package/LICENSE.md +9 -0
  3. package/README.md +237 -2
  4. package/package.json +161 -3
  5. package/src/build-dev/cli/add/addServerHook.js +30 -0
  6. package/src/build-dev/cli/add/addTypeRef.js +19 -0
  7. package/src/build-dev/cli/add/updateGitIgnore.js +33 -0
  8. package/src/build-dev/cli/add/updatePackageJson.js +26 -0
  9. package/src/build-dev/cli/add/updateSvelteConfig.js +199 -0
  10. package/src/build-dev/cli/add/updateViteConfig.js +152 -0
  11. package/src/build-dev/cli/add.js +95 -0
  12. package/src/build-dev/cli/build.js +30 -0
  13. package/src/build-dev/cli/dev.js +49 -0
  14. package/src/build-dev/cli/index.js +14 -0
  15. package/src/build-dev/cli/upgrade.js +54 -0
  16. package/src/build-dev/svelte/index.js +54 -0
  17. package/src/build-dev/svelte/lib/isTargetFile.js +6 -0
  18. package/src/build-dev/svelte/metadatas.js +39 -0
  19. package/src/build-dev/svelte/processors/addBasePathToHrefAndSrc/addBasePathToHrefAndSrc.js +29 -0
  20. package/src/build-dev/svelte/processors/addBasePathToHrefAndSrc/addBasePathToHrefAndSrc.spec.js +82 -0
  21. package/src/build-dev/svelte/processors/addScriptTags.js +17 -0
  22. package/src/build-dev/svelte/processors/convertToHtml/convertToHtml.js +19 -0
  23. package/src/build-dev/svelte/processors/convertToHtml/convertToHtml.spec.js +123 -0
  24. package/src/build-dev/svelte/processors/convertToHtml/processMarkdown.js +59 -0
  25. package/src/build-dev/svelte/processors/extractQueries/extractQueries.js +49 -0
  26. package/src/build-dev/svelte/processors/extractQueries/extractQueries.spec.js +54 -0
  27. package/src/build-dev/svelte/processors/highlight/highlight.js +52 -0
  28. package/src/build-dev/svelte/processors/highlight/highlight.spec.js +31 -0
  29. package/src/build-dev/svelte/processors/initializeUniversalSql.js +15 -0
  30. package/src/build-dev/svelte/processors/injectComponents/injectComponents.js +56 -0
  31. package/src/build-dev/svelte/processors/injectHighlightStyles.js +14 -0
  32. package/src/build-dev/svelte/processors/injectQueries/injectQueries.js +77 -0
  33. package/src/build-dev/svelte/processors/markRootLayoutPrerenderable.js +56 -0
  34. package/src/build-dev/svelte/processors/obfuscateCode/obfuscateCode.js +17 -0
  35. package/src/build-dev/svelte/processors/obfuscateCode/obfuscateCode.spec.js +21 -0
  36. package/src/build-dev/svelte/processors/transformQueries/transformQueries.js +58 -0
  37. package/src/build-dev/vite/config-virtual.js +24 -0
  38. package/src/build-dev/vite/constants.js +7 -0
  39. package/src/build-dev/vite/datasource-plugins/source-query-hmr.js +117 -0
  40. package/src/build-dev/vite/evidence-config.d.ts +6 -0
  41. package/src/build-dev/vite/index.js +214 -0
  42. package/src/build-dev/vite/layout-plugins/copy-to-layout.js +71 -0
  43. package/src/build-dev/vite/plugins.js +4 -0
  44. package/src/build-dev/vite/query-directory-hmr.js +32 -0
  45. package/src/build-dev/vite/sidecar-app.js +79 -0
  46. package/src/build-dev/vite/virtuals/QuerySSR.svelte +13 -0
  47. package/src/build-dev/vite/virtuals/__tests/proxyStack.spec.js +52 -0
  48. package/src/build-dev/vite/virtuals/bootstrapContexts.svelte.js +27 -0
  49. package/src/build-dev/vite/virtuals/browser/static-assets.js +3 -0
  50. package/src/build-dev/vite/virtuals/contextKeys.js +3 -0
  51. package/src/build-dev/vite/virtuals/initUsql.js +23 -0
  52. package/src/build-dev/vite/virtuals/node/static-assets.js +56 -0
  53. package/src/build-dev/vite/virtuals/proxyStack.js +37 -0
  54. package/src/build-dev/vite/virtuals/queries.svelte.js +150 -0
  55. package/src/build-dev/vite/virtuals/ssrHook.svelte.js +60 -0
  56. package/src/build-dev/vite/virtuals/updateQueryContext.svelte.js +31 -0
  57. package/src/build-dev/vite/virtuals-dynamic.js +12 -0
  58. package/src/cli.js +5 -0
  59. package/src/cli.root.js +90 -0
  60. package/src/configuration/cli/create.js +20 -0
  61. package/src/configuration/cli/index.js +12 -0
  62. package/src/configuration/createEvidenceConfig.js +51 -0
  63. package/src/configuration/getEvidenceConfig.js +60 -0
  64. package/src/configuration/getEvidenceConfig.legacy.js +27 -0
  65. package/src/configuration/index.js +1 -0
  66. package/src/configuration/schemas/config.schema.js +11 -0
  67. package/src/configuration/schemas/deployment.schema.js +9 -0
  68. package/src/configuration/schemas/deployment.schema.spec.js +34 -0
  69. package/src/configuration/updateEvidenceConfig.js +25 -0
  70. package/src/legacy-compat.js +8 -0
  71. package/src/lib/EvidenceError.js +35 -0
  72. package/src/lib/b64Deep.js +55 -0
  73. package/src/lib/check-import.js +12 -0
  74. package/src/lib/cleanZodErrors.js +22 -0
  75. package/src/lib/cli/cmdFail.js +33 -0
  76. package/src/lib/cli/notices.js +44 -0
  77. package/src/lib/debug.js +40 -0
  78. package/src/lib/flows.d.ts +21 -0
  79. package/src/lib/forceLink.js +28 -0
  80. package/src/lib/history/index.js +70 -0
  81. package/src/lib/history/types.d.ts +8 -0
  82. package/src/lib/pkg-types.helpers.js +16 -0
  83. package/src/lib/processing-queue.js +96 -0
  84. package/src/lib/processing-queue.spec.js +148 -0
  85. package/src/lib/projectPaths.js +29 -0
  86. package/src/lib/projectRoot.js +12 -0
  87. package/src/lib/sharedPromise.js +77 -0
  88. package/src/lib/sharedPromise.spec.js +23 -0
  89. package/src/lib/strict.js +19 -0
  90. package/src/lib/tests/fs.js +21 -0
  91. package/src/lib/tokens.js +7 -0
  92. package/src/lib/unnest-zod-error.js +14 -0
  93. package/src/logger/EvidenceLogger.js +164 -0
  94. package/src/logger/index.js +4 -0
  95. package/src/meta.js +8 -0
  96. package/src/plugins/cli/index.js +13 -0
  97. package/src/plugins/cli/install.js +26 -0
  98. package/src/plugins/cli/install.prompt.js +121 -0
  99. package/src/plugins/components/getAllComponents.js +82 -0
  100. package/src/plugins/components/getComponentsInPlugin.js +33 -0
  101. package/src/plugins/components/loadComponentPlugins.js +48 -0
  102. package/src/plugins/components/loaders/file-loader.js +125 -0
  103. package/src/plugins/components/loaders/manifest-loader.js +53 -0
  104. package/src/plugins/components/schemas/component-manifest.schema.js +5 -0
  105. package/src/plugins/components/types.d.ts +21 -0
  106. package/src/plugins/components/validateOverrides.js +30 -0
  107. package/src/plugins/components/validateOverrides.spec.js +32 -0
  108. package/src/plugins/datasources/Datasources.js +85 -0
  109. package/src/plugins/datasources/Datasources.spec.js +78 -0
  110. package/src/plugins/datasources/SourceResultCache.js +62 -0
  111. package/src/plugins/datasources/buildSourceDirectoryProxy.js +21 -0
  112. package/src/plugins/datasources/cli/edit/Options.fixtures.js +69 -0
  113. package/src/plugins/datasources/cli/edit/Options.js +253 -0
  114. package/src/plugins/datasources/cli/edit/Options.spec.js +496 -0
  115. package/src/plugins/datasources/cli/edit/editSourceConfig.js +201 -0
  116. package/src/plugins/datasources/cli/edit.js +20 -0
  117. package/src/plugins/datasources/cli/edit.prompt.js +100 -0
  118. package/src/plugins/datasources/cli/index.js +18 -0
  119. package/src/plugins/datasources/cli/sources.js +77 -0
  120. package/src/plugins/datasources/evalSources.js +257 -0
  121. package/src/plugins/datasources/getPublishedDatasources.js +62 -0
  122. package/src/plugins/datasources/index.js +6 -0
  123. package/src/plugins/datasources/loadSourceConfig.js +147 -0
  124. package/src/plugins/datasources/loadSourceConfig.spec.js +127 -0
  125. package/src/plugins/datasources/loadSourcePlugins.js +49 -0
  126. package/src/plugins/datasources/loadSources.js +48 -0
  127. package/src/plugins/datasources/schemas/datasource.schema.js +52 -0
  128. package/src/plugins/datasources/schemas/datasourceCache.schema.js +3 -0
  129. package/src/plugins/datasources/schemas/datasourcePlugin.schema.js +37 -0
  130. package/src/plugins/datasources/schemas/datasourcePluginOptions.schema.js +64 -0
  131. package/src/plugins/datasources/schemas/index.js +2 -0
  132. package/src/plugins/datasources/schemas/manifest.schema.js +8 -0
  133. package/src/plugins/datasources/schemas/results.schema.js +126 -0
  134. package/src/plugins/datasources/sub-source-vars.js +55 -0
  135. package/src/plugins/datasources/sub-source-vars.spec.js +46 -0
  136. package/src/plugins/datasources/types.d.ts +53 -0
  137. package/src/plugins/datasources/updateManifest.js +115 -0
  138. package/src/plugins/datasources/updateManifest.spec.js +200 -0
  139. package/src/plugins/datasources/wrapSimpleConnector.js +95 -0
  140. package/src/plugins/datasources/writeSourceConfig.js +60 -0
  141. package/src/plugins/index.js +2 -0
  142. package/src/plugins/layouts/copyMethods/index.js +10 -0
  143. package/src/plugins/layouts/copyMethods/svelte.js +53 -0
  144. package/src/plugins/layouts/copyMethods/sveltekit.js +75 -0
  145. package/src/plugins/layouts/copyToLayout.js +106 -0
  146. package/src/plugins/layouts/loadLayoutPlugin.js +23 -0
  147. package/src/plugins/loadPluginPackage.js +77 -0
  148. package/src/plugins/schemas/index.js +1 -0
  149. package/src/plugins/schemas/plugin-config.schema.js +41 -0
  150. package/src/plugins/schemas/plugin-config.schema.spec.js +21 -0
  151. package/src/plugins/schemas/plugin-package.schema.js +154 -0
  152. package/src/plugins/schemas/plugin-package.schema.spec.js +30 -0
  153. package/src/query-builder.d.ts +1 -0
  154. package/src/query-builder.js +1 -0
  155. package/src/types/duckdb-wellknown.d.ts +35 -0
  156. package/src/types/html-attributes.ts +13 -0
  157. package/src/types/index.d.ts +18 -0
  158. package/src/types/mosaic-sql.d.ts +27 -0
  159. package/src/types/sveltekit-autoimport.d.ts +13 -0
  160. package/src/types/virtuals.d.ts +113 -0
  161. package/src/types.d.ts +1 -0
  162. package/src/usql/index.d.ts +4 -0
  163. package/src/usql/index.js +3 -0
  164. package/src/usql/query/Query.js +1391 -0
  165. package/src/usql/query/Query.spec.js +827 -0
  166. package/src/usql/query/queryScore.js +92 -0
  167. package/src/usql/query/queryScore.spec.js +26 -0
  168. package/src/usql/query/sterilizeQuery.js +89 -0
  169. package/src/usql/query/sterilizeQuery.spec.js +172 -0
  170. package/src/usql/setTrackProxy/setTrackProxy.js +80 -0
  171. package/src/usql/setTrackProxy/setTrackProxy.spec.js +166 -0
  172. package/src/usql/types.ts +86 -0
  173. package/src/usql/utilities/duckdbSerialize.js +29 -0
  174. package/src/usql/utilities/index.js +2 -0
  175. package/src/usql/utilities/resolveMaybePromise.js +30 -0
  176. package/src/utils/batchUp.js +22 -0
  177. package/src/utils/batchUp.spec.js +69 -0
  178. package/src/utils/browserDebounce.js +16 -0
  179. package/src/utils/index.js +7 -0
  180. package/src/utils/svelte/addBasePath.js +45 -0
  181. package/src/utils/svelte/addBasePath.spec.js +86 -0
  182. package/src/utils/svelte/index.js +5 -0
  183. package/src/utils/svelte/inputs.js +138 -0
  184. package/tsconfig.json +22 -0
  185. package/vite.config.js +3 -0
  186. package/vitest.config.js +15 -0
@@ -0,0 +1,96 @@
1
+ import EventEmitter from 'events';
2
+
3
+ /** @typedef {"done" | "err"} ProcessingQueueEvent */
4
+
5
+ /**
6
+ * @typedef {Object} ProcessingQueueOpts
7
+ * @property {boolean} [stopOnError]
8
+ */
9
+
10
+ /**
11
+ * @param {ProcessingQueueOpts} param0
12
+ */
13
+ export const ProcessingQueue = ({ stopOnError } = {}) => {
14
+ /** @type {(() => unknown)[]} */
15
+ const queue = [];
16
+ /** @type {boolean} */
17
+ let running = false;
18
+
19
+ /** @type {boolean} */
20
+ let frozen = false;
21
+
22
+ const emitter = new EventEmitter();
23
+ if (stopOnError) emitter.addListener('err', () => (frozen = true));
24
+
25
+ /**
26
+ * @returns {Promise<void>}
27
+ */
28
+ const next = async () => {
29
+ if (frozen) {
30
+ running = false;
31
+ return;
32
+ }
33
+ running = true;
34
+ if (queue.length) {
35
+ try {
36
+ const fn = queue.pop();
37
+ if (fn === undefined) {
38
+ console.error('Something has gone awry!'); // TODO: This error message sucks
39
+ return;
40
+ }
41
+
42
+ const result = fn();
43
+ if (result instanceof Promise) await result;
44
+ } catch (e) {
45
+ emitter.emit('err', e);
46
+ }
47
+
48
+ await next();
49
+ } else {
50
+ emitter.emit('done');
51
+ running = false;
52
+ }
53
+ };
54
+
55
+ return {
56
+ /**
57
+ * @param {Array<() => unknown>} fn
58
+ * @returns {Promise<void>} Promise resolves when the queue has emptied; will throw if an error is encountered
59
+ */
60
+ add(...fn) {
61
+ queue.push(...fn);
62
+ if (!running) {
63
+ return next();
64
+ }
65
+ return Promise.resolve();
66
+ },
67
+ get frozen() {
68
+ return frozen;
69
+ },
70
+ /**
71
+ * @param {ProcessingQueueEvent} event
72
+ * @param {Parameters<EventEmitter["addListener"]>[1]} handler
73
+ */
74
+ addListener: (event, handler) => {
75
+ emitter.addListener(event, handler);
76
+ },
77
+ /**
78
+ * @param {ProcessingQueueEvent} event
79
+ * @param {Parameters<EventEmitter["removeListener"]>[1]} handler
80
+ */
81
+ removeListener: (event, handler) => {
82
+ emitter.removeListener(event, handler);
83
+ },
84
+ removeAllListeners: emitter.removeAllListeners.bind(emitter),
85
+ finish: async () => {
86
+ return /** @type {Promise<void>} */ (
87
+ new Promise((res, rej) => {
88
+ if (running) {
89
+ emitter.addListener('done', res);
90
+ emitter.addListener('err', rej);
91
+ } else res();
92
+ })
93
+ );
94
+ }
95
+ };
96
+ };
@@ -0,0 +1,148 @@
1
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import { ProcessingQueue } from './processing-queue';
3
+
4
+ describe('ProcessingQueue', () => {
5
+ const testFn = vi.fn();
6
+
7
+ beforeEach(() => {
8
+ vi.resetAllMocks();
9
+ });
10
+
11
+ it('Should be defined', () => {
12
+ expect(ProcessingQueue).toBeDefined();
13
+ });
14
+ it('Should execute a syncronous function', () => {
15
+ const q = ProcessingQueue();
16
+
17
+ q.add(testFn);
18
+
19
+ expect(testFn).toHaveBeenCalledOnce();
20
+ });
21
+
22
+ it('Should execute an async function', () => {
23
+ const q = ProcessingQueue();
24
+ testFn.mockImplementation(async () => {});
25
+ q.add(testFn);
26
+
27
+ expect(testFn).toHaveBeenCalledOnce();
28
+ });
29
+
30
+ it('Should emit a `done` event when all functions have been processed', () => {
31
+ const q = ProcessingQueue();
32
+ const eventListener = vi.fn();
33
+ q.addListener('done', eventListener);
34
+ q.add(testFn);
35
+ expect(testFn).toHaveBeenCalledOnce();
36
+ expect(eventListener).toHaveBeenCalledOnce();
37
+ });
38
+
39
+ it('Should execute multiple sync functions', async () => {
40
+ const q = ProcessingQueue();
41
+
42
+ q.add(testFn, testFn);
43
+
44
+ expect(testFn).toHaveBeenCalledTimes(2);
45
+ });
46
+
47
+ it('Should execute multiple async functions', async () => {
48
+ const q = ProcessingQueue();
49
+ testFn.mockImplementation(async () => {});
50
+ q.add(testFn, testFn);
51
+ // Wait for async
52
+ await q.finish();
53
+
54
+ expect(testFn).toHaveBeenCalledTimes(2);
55
+ });
56
+
57
+ it('Should execute multiple syncronous functions when queued separately', async () => {
58
+ const q = ProcessingQueue();
59
+
60
+ testFn.toString = () => 'MockedFn';
61
+ q.add(testFn, testFn);
62
+ q.add(testFn, testFn);
63
+ q.add(testFn, testFn);
64
+ await q.finish();
65
+
66
+ expect(testFn).toHaveBeenCalledTimes(6);
67
+ });
68
+
69
+ it('Should execute multiple async functions when queued separately', async () => {
70
+ const q = ProcessingQueue();
71
+ testFn.mockImplementation(async () => {});
72
+ q.add(testFn, testFn);
73
+ q.add(testFn, testFn);
74
+ q.add(testFn, testFn);
75
+ // Wait for async
76
+ await q.finish();
77
+
78
+ expect(testFn).toHaveBeenCalledTimes(6);
79
+ });
80
+
81
+ it('Should execute a mix of sync & async functions', async () => {
82
+ const q = ProcessingQueue();
83
+ const asyncTest = vi.fn().mockImplementation(async () => {});
84
+ q.add(testFn, asyncTest);
85
+ // Wait for async
86
+ await q.finish();
87
+
88
+ expect(testFn).toHaveBeenCalledTimes(1);
89
+ expect(asyncTest).toHaveBeenCalledTimes(1);
90
+ });
91
+
92
+ it('Should execute a mix of sync & async functions when queued separately', async () => {
93
+ const q = ProcessingQueue();
94
+ const asyncTest = vi.fn().mockImplementation(async () => {});
95
+ q.add(testFn, asyncTest);
96
+ q.add(testFn, asyncTest);
97
+ q.add(testFn, asyncTest);
98
+ // Wait for async
99
+ await q.finish();
100
+
101
+ expect(testFn).toHaveBeenCalledTimes(3);
102
+ expect(asyncTest).toHaveBeenCalledTimes(3);
103
+ });
104
+
105
+ it('Should handle a syncronous function that throws an error', async () => {
106
+ const q = ProcessingQueue();
107
+ const innerError = new Error('Hello!');
108
+ testFn.mockImplementation(() => {
109
+ throw innerError;
110
+ });
111
+ const eventListener = vi.fn();
112
+ q.addListener('err', eventListener);
113
+
114
+ q.add(testFn);
115
+ expect(testFn).toHaveBeenCalledOnce();
116
+ expect(eventListener).toHaveBeenCalledWith(innerError);
117
+ });
118
+
119
+ it('Should handle an asyncronous function that throws an error', async () => {
120
+ const q = ProcessingQueue();
121
+ const innerError = new Error('Hello!');
122
+ testFn.mockImplementation(async () => {
123
+ throw innerError;
124
+ });
125
+ const eventListener = vi.fn();
126
+ q.addListener('err', eventListener);
127
+
128
+ // Waiting for this _will_ wait for the queue to empty
129
+ await q.add(testFn);
130
+ expect(testFn).toHaveBeenCalledOnce();
131
+ expect(eventListener).toHaveBeenCalledWith(innerError);
132
+ });
133
+
134
+ it('Should stop execution when it encounters an error and stopOnError is true', async () => {
135
+ const q = ProcessingQueue({ stopOnError: true });
136
+ const innerError = new Error('Hello!');
137
+ testFn.mockImplementationOnce(async () => {
138
+ throw innerError;
139
+ });
140
+
141
+ q.add(testFn);
142
+ testFn.mockImplementationOnce(async () => {});
143
+ // This should not actually get called, stopOnError, and the error above, means that the queue will freeze.
144
+ await q.add(testFn);
145
+
146
+ expect(testFn).toHaveBeenCalledOnce();
147
+ });
148
+ });
@@ -0,0 +1,29 @@
1
+ import path from 'path';
2
+
3
+ export const URL_PREFIX =
4
+ 'EVIDENCE_URL_PREFIX' in process.env ? process.env.EVIDENCE_URL_PREFIX : '_evidence';
5
+
6
+ export const inTemplate = process.cwd().includes(path.join('.evidence', 'template'));
7
+
8
+ export const evidenceDirectory = inTemplate ? '..' : '.evidence';
9
+
10
+ export const dataDirectory =
11
+ 'EVIDENCE_DATA_DIR' in process.env && process.env.EVIDENCE_DATA_DIR
12
+ ? path.resolve(process.env.EVIDENCE_DATA_DIR)
13
+ : path.resolve(evidenceDirectory, 'data');
14
+
15
+ export const dataUrlPrefix =
16
+ 'EVIDENCE_DATA_URL_PREFIX' in process.env
17
+ ? process.env.EVIDENCE_DATA_URL_PREFIX
18
+ : `/${URL_PREFIX}/query`;
19
+
20
+ export const metaDirectory = path.resolve(evidenceDirectory, 'meta');
21
+
22
+ export const projectRoot = path.resolve(...(inTemplate ? ['..', '..'] : []));
23
+
24
+ export const sourcesDirectory = path.resolve(projectRoot, 'sources');
25
+
26
+ export const pagesDirectory =
27
+ 'EVIDENCE_PAGES_DIR' in process.env && process.env.EVIDENCE_PAGES_DIR
28
+ ? path.resolve(process.env.EVIDENCE_PAGES_DIR)
29
+ : path.resolve(projectRoot, 'pages');
@@ -0,0 +1,12 @@
1
+ import path from 'path';
2
+
3
+ let _init = process.cwd();
4
+ // If we are in a template, strip that part of the URL out
5
+ if (_init.endsWith(path.join('.evidence', 'template'))) {
6
+ _init = _init.substring(0, _init.length - path.join('.evidence', 'template').length);
7
+ }
8
+
9
+ /**
10
+ * @deprecated Use projectRoot from "projectPaths.js" instead
11
+ */
12
+ export const projectRoot = _init;
@@ -0,0 +1,77 @@
1
+ /**
2
+ * @template [ResolveType=unknown]
3
+ * @typedef {Object} SharedPromise
4
+ * @property {Promise<ResolveType>} promise
5
+ * @property {(v: ResolveType) => unknown} resolve
6
+ * @property {(e: Error) => unknown} reject
7
+ * @property {'init' | 'loading' | 'resolved' | 'rejected'} state
8
+ * @property {ResolveType | null} value
9
+ * @property {() => void} start
10
+ **/
11
+
12
+ /**
13
+ * @template [ResolveType=void]
14
+ * @param {() => void} [stateChangeHook]
15
+ * @returns {SharedPromise<ResolveType>}
16
+ */
17
+ export const sharedPromise = (stateChangeHook) => {
18
+ /** @type {((v: ResolveType) => unknown) | null} */
19
+ let res = null;
20
+ /** @type {((e: Error) => unknown) | null} */
21
+ let rej = null;
22
+ /** @type {Promise<ResolveType>} */
23
+ const p = new Promise((a, b) => {
24
+ res = a;
25
+ rej = b;
26
+ });
27
+
28
+ /** @type {'init' | 'loading' | 'resolved' | 'rejected'} */
29
+ let state = 'init';
30
+
31
+ /**
32
+ * @type {ResolveType | null}
33
+ */
34
+ let resolvedValue = null;
35
+
36
+ if (!res || !rej) throw new Error();
37
+ return {
38
+ promise: p,
39
+ /**
40
+ * @param {ResolveType} v
41
+ */
42
+ resolve: (v) => {
43
+ if (res) {
44
+ if (state === 'loading' || state === 'init') {
45
+ state = 'resolved';
46
+ resolvedValue = v;
47
+ res(v);
48
+ stateChangeHook?.();
49
+ }
50
+ } else throw new Error('SharedPromise encountered an error: res not defined');
51
+ },
52
+ /**
53
+ *
54
+ * @param {Error} e
55
+ */
56
+ reject: (e) => {
57
+ if (rej) {
58
+ if (state === 'loading' || state === 'init') {
59
+ state = 'rejected';
60
+ p.catch(() => {}); // noop to prevent the page from dying. This does not prevent .catch from working in other places
61
+ rej(e);
62
+ stateChangeHook?.();
63
+ }
64
+ } else throw new Error('SharedPromise encountered an error: rej not defined');
65
+ },
66
+ get state() {
67
+ return state;
68
+ },
69
+ get value() {
70
+ return resolvedValue;
71
+ },
72
+ start() {
73
+ state = 'loading';
74
+ stateChangeHook?.();
75
+ }
76
+ };
77
+ };
@@ -0,0 +1,23 @@
1
+ import { it, describe, vi, expect } from 'vitest';
2
+ import { sharedPromise } from './sharedPromise';
3
+
4
+ describe('sharedPromise', () => {
5
+ it('should not call the state change hook if the promise has landed (resolve)', () => {
6
+ const hook = vi.fn();
7
+ const promise = sharedPromise(hook);
8
+
9
+ promise.start();
10
+ promise.resolve([]);
11
+ promise.resolve([]);
12
+ expect(hook).toHaveBeenCalledTimes(2);
13
+ });
14
+ it('should not call the state change hook if the promise has landed (reject)', () => {
15
+ const hook = vi.fn();
16
+ const promise = sharedPromise(hook);
17
+ promise.promise.catch(() => {});
18
+ promise.start();
19
+ promise.reject(new Error());
20
+ promise.reject(new Error());
21
+ expect(hook).toHaveBeenCalledTimes(2);
22
+ });
23
+ });
@@ -0,0 +1,19 @@
1
+ import { log } from '../logger/index.js';
2
+ import { EvidenceError } from './EvidenceError.js';
3
+
4
+ export const enableStrictMode = () => {
5
+ if (typeof process === 'undefined') {
6
+ throw new Error('Strict mode must be enabled server-side');
7
+ }
8
+ log.info('Enabling strict mode');
9
+ process.env.EVIDENCE_STRICT_MODE = 'true';
10
+ };
11
+
12
+ export const isStrictMode = () => {
13
+ if (typeof process !== 'undefined') return Boolean(process.env.EVIDENCE_STRICT_MODE);
14
+ if (typeof import.meta.env !== 'undefined') return Boolean(import.meta.env.EVIDENCE_STRICT_MODE);
15
+ throw new EvidenceError('Unable to identify if strict mode is enabled', [
16
+ 'process is undefined',
17
+ 'import.meta.env is undefined'
18
+ ]);
19
+ };
@@ -0,0 +1,21 @@
1
+ import { vi } from 'vitest';
2
+ import { vol } from 'memfs';
3
+
4
+ vi.mock('fs', () => {
5
+ return {
6
+ default: vol,
7
+ ...vol
8
+ };
9
+ });
10
+ vi.mock('fs/promises', () => {
11
+ return {
12
+ default: vol.promises,
13
+ ...vol.promises
14
+ };
15
+ });
16
+
17
+ export const writeFs = vol.fromNestedJSON.bind(vol);
18
+
19
+ export const resetFs = () => {
20
+ vol.reset();
21
+ };
@@ -0,0 +1,7 @@
1
+ import chalk from 'chalk';
2
+
3
+ export const logWarn = chalk.yellow('[!]');
4
+ export const logError = chalk.red('[!]');
5
+ export const logFatal = chalk.bgRed.white('[ ! ]');
6
+
7
+ export const redPipe = chalk.red('|');
@@ -0,0 +1,14 @@
1
+ /**
2
+ * @param {import("zod").ZodError} e
3
+ * @returns {Record<string, string>}
4
+ */
5
+ export const unnestZodError = (e) => {
6
+ /** @type {Record<string, string>} */
7
+ const out = {};
8
+ for (const issue of e.issues) {
9
+ const path = issue.path.join('.');
10
+ if (out[path]) continue;
11
+ out[path] = issue.message;
12
+ }
13
+ return out;
14
+ };
@@ -0,0 +1,164 @@
1
+ import { isDebug, onEnableDebug } from '../lib/debug.js';
2
+
3
+ /**
4
+ * @typedef {Object} LogDriver
5
+ * @property {(level: keyof EvidenceLogger.EvidenceLogLevels, message: string, meta: any) => unknown} log
6
+ */
7
+
8
+ export class EvidenceLogger {
9
+ static EvidenceLogLevels = {
10
+ fatal: 0,
11
+ error: 1,
12
+ warn: 2,
13
+ info: 3,
14
+ debug: 4,
15
+ verbose: 5
16
+ };
17
+
18
+ /** @type {LogDriver} */
19
+ #logger;
20
+
21
+ /** @type {EvidenceLogger.EvidenceLogLevels[keyof EvidenceLogger.EvidenceLogLevels]} */
22
+ logLevel = 3;
23
+ constructor() {
24
+ onEnableDebug(() => (this.logLevel = 4));
25
+ // TODO: Add winston, pino, or a similar library (?)
26
+ this.#logger = {
27
+ /**
28
+ *
29
+ * @param {keyof typeof EvidenceLogger.EvidenceLogLevels} level
30
+ * @param {string} message
31
+ * @param {Record<string, any>} meta
32
+ */
33
+ log: (level, message, meta) => {
34
+ /** @type {any[]} */
35
+ const args = [message];
36
+ if (meta) args.push(meta);
37
+ if (EvidenceLogger.EvidenceLogLevels[level] > this.logLevel) return;
38
+ switch (level) {
39
+ case 'fatal':
40
+ case 'error':
41
+ console.error(`[${level.toUpperCase()}]: `, ...args);
42
+ break;
43
+ case 'warn':
44
+ console.warn(`[${level.toUpperCase()}]: `, ...args);
45
+ break;
46
+ default:
47
+ case 'info':
48
+ console.info(`[${level.toUpperCase()}]: `, ...args);
49
+ break;
50
+ case 'debug':
51
+ console.debug(`[${level.toUpperCase()}]: `, ...args);
52
+ break;
53
+ case 'verbose':
54
+ console.debug(`[${level.toUpperCase()}]: `, ...args);
55
+ break;
56
+ }
57
+ }
58
+ };
59
+ }
60
+
61
+ /**
62
+ * @param {string} message
63
+ * @param {string[]} [detail]
64
+ * @param {Record<string, any>} [meta]
65
+ * @param {Record<string, any>} [debugMeta]
66
+ */
67
+ die(message, detail, meta, debugMeta) {
68
+ this.fatal(`${message}\n${detail ? detail.join('\n') : ''}`, {
69
+ ...meta,
70
+ ...(isDebug() ? debugMeta : {})
71
+ });
72
+ if (typeof process !== 'undefined') process.exit(1);
73
+ }
74
+
75
+ /**
76
+ *
77
+ * @param {keyof typeof EvidenceLogger.EvidenceLogLevels} level
78
+ * @returns {(message: string, meta?: Record<string, any>) => void}
79
+ */
80
+ #log = (level) => (message, meta) => {
81
+ let out = message;
82
+ this.#logger.log(level, out, meta);
83
+ };
84
+
85
+ /**
86
+ * @param {string} message
87
+ * @param {Record<string, any>} [meta]
88
+ */
89
+ fatal = this.#log('fatal');
90
+
91
+ /**
92
+ * @param {string} message
93
+ * @param {Record<string, any>} [meta]
94
+ */
95
+ error = this.#log('error');
96
+
97
+ /**
98
+ * @param {string} message
99
+ * @param {Record<string, any>} [meta]
100
+ */
101
+ warn = this.#log('warn');
102
+
103
+ /**
104
+ * @param {string} message
105
+ * @param {Record<string, any>} [meta]
106
+ */
107
+ info = this.#log('info');
108
+
109
+ /**
110
+ * @param {string} message
111
+ * @param {Record<string, any>} [meta]
112
+ */
113
+ debug = this.#log('debug');
114
+
115
+ /**
116
+ * @param {string} message
117
+ * @param {Record<string, any>} [meta]
118
+ */
119
+ verbose = this.#log('verbose');
120
+
121
+ /** @type {string[]} */
122
+ #measureStack = [];
123
+
124
+ /**
125
+ * @param {string} topic
126
+ * @returns
127
+ */
128
+ measure = (topic) => {
129
+ if (!isDebug()) {
130
+ return {
131
+ meta: () => {},
132
+ done: () => {}
133
+ };
134
+ }
135
+
136
+ // Start
137
+ const before = performance.now();
138
+ /** @type {Record<string, any>} */
139
+ const meta = {};
140
+
141
+ this.#measureStack.push(topic);
142
+
143
+ return {
144
+ /**
145
+ * @param {string} key
146
+ * @param {any} value
147
+ */
148
+ meta: (key, value) => {
149
+ meta[key] = value;
150
+ },
151
+ done: () => {
152
+ const after = performance.now();
153
+ const duration = after - before;
154
+
155
+ this.#measureStack.pop();
156
+ this.#log('debug')(`Measure: "${topic}"`, {
157
+ duration,
158
+ meta,
159
+ parents: this.#measureStack
160
+ });
161
+ }
162
+ };
163
+ };
164
+ }
@@ -0,0 +1,4 @@
1
+ import { EvidenceLogger } from './EvidenceLogger.js';
2
+ export { EvidenceLogger };
3
+
4
+ export const log = new EvidenceLogger();
package/src/meta.js ADDED
@@ -0,0 +1,8 @@
1
+ export * as paths from './lib/projectPaths.js';
2
+ let isExampleProject = false;
3
+
4
+ if (process.cwd().endsWith('sites/example-project')) {
5
+ isExampleProject = true;
6
+ }
7
+
8
+ export { isExampleProject };
@@ -0,0 +1,13 @@
1
+ import { install } from './install.js';
2
+
3
+ /**
4
+ * @type {import("@brianmd/citty").SubCommandsDef}
5
+ */
6
+ export const pluginsCli = {
7
+ plugins: {
8
+ meta: { name: 'plugins', description: "Manage your project's Evidence Plugins" },
9
+ subCommands: {
10
+ install
11
+ }
12
+ }
13
+ };
@@ -0,0 +1,26 @@
1
+ import * as prompt from '@clack/prompts';
2
+ import { installPluginPrompt } from './install.prompt.js';
3
+
4
+ /** @type {import("@brianmd/citty").CommandDef} */
5
+ export const install = {
6
+ meta: {
7
+ name: 'Install',
8
+ description: 'Utility to install or remove Evidence plugins'
9
+ },
10
+ async run() {
11
+ prompt.intro('Install or Remove Evidence Plugins');
12
+
13
+ // eslint-disable-next-line no-constant-condition
14
+ while (true) {
15
+ if (!(await installPluginPrompt())) return;
16
+
17
+ const again = await prompt.confirm({
18
+ message: 'Would you like to install another plugin?',
19
+ initialValue: false
20
+ });
21
+ if (!again || prompt.isCancel(again)) break;
22
+ }
23
+
24
+ prompt.outro('Done!');
25
+ }
26
+ };