nuxt-files-sdk 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/config/prune.js
CHANGED
|
@@ -1,14 +1,16 @@
|
|
|
1
1
|
import { dirname, resolve } from "node:path";
|
|
2
|
-
import {
|
|
2
|
+
import { parseSync } from "oxc-parser";
|
|
3
3
|
//#region src/config/prune.ts
|
|
4
4
|
const unwrap = (node) => node.type === "TSAsExpression" || node.type === "TSSatisfiesExpression" || node.type === "ParenthesizedExpression" ? unwrap(node.expression) : node;
|
|
5
5
|
const keyOf = (node) => node.key?.type === "Identifier" ? node.key.name : typeof node.key?.value === "string" ? node.key.value : void 0;
|
|
6
6
|
/** Remove inactive environment literals before bundling the user config. */
|
|
7
7
|
const pruneFilesConfigSource = (source, configPath, environments) => {
|
|
8
|
-
const
|
|
8
|
+
const parsed = parseSync(configPath, source, {
|
|
9
9
|
sourceType: "module",
|
|
10
|
-
|
|
11
|
-
})
|
|
10
|
+
lang: "ts"
|
|
11
|
+
});
|
|
12
|
+
if (parsed.errors.length > 0) throw new Error(`[nuxt-files-sdk:invalid-config] ${parsed.errors[0].message}`);
|
|
13
|
+
const body = parsed.program.body;
|
|
12
14
|
const exported = body.find((node) => node.type === "ExportDefaultDeclaration")?.declaration;
|
|
13
15
|
if (!exported) throw new Error("[nuxt-files-sdk:invalid-config] files.config.ts needs a default export.");
|
|
14
16
|
let root = unwrap(exported);
|
package/dist/config/prune.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prune.js","names":[],"sources":["../../src/config/prune.ts"],"sourcesContent":["import { dirname, resolve } from 'node:path'\n\nimport {
|
|
1
|
+
{"version":3,"file":"prune.js","names":[],"sources":["../../src/config/prune.ts"],"sourcesContent":["import { dirname, resolve } from 'node:path'\n\nimport { parseSync } from 'oxc-parser'\n\ninterface SyntaxNode {\n type: string\n start: number\n end: number\n name?: string\n value?: unknown\n key?: SyntaxNode\n source?: SyntaxNode\n declaration?: SyntaxNode\n declarations?: SyntaxNode[]\n id?: SyntaxNode\n init?: SyntaxNode\n expression?: SyntaxNode\n callee?: SyntaxNode\n arguments?: SyntaxNode[]\n properties?: SyntaxNode[]\n body?: SyntaxNode[]\n}\n\nconst unwrap = (node: SyntaxNode): SyntaxNode =>\n node.type === 'TSAsExpression' || node.type === 'TSSatisfiesExpression' || node.type === 'ParenthesizedExpression'\n ? unwrap(node.expression!)\n : node\nconst keyOf = (node: SyntaxNode): string | undefined =>\n node.key?.type === 'Identifier' ? node.key.name : typeof node.key?.value === 'string' ? node.key.value : undefined\n\n/** Remove inactive environment literals before bundling the user config. */\nexport const pruneFilesConfigSource = (source: string, configPath: string, environments: readonly string[]): string => {\n const parsed = parseSync(configPath, source, { sourceType: 'module', lang: 'ts' })\n if (parsed.errors.length > 0) {\n throw new Error(`[nuxt-files-sdk:invalid-config] ${parsed.errors[0]!.message}`)\n }\n // Oxc's node union is wider than the fields inspected here.\n // oxlint-disable typescript/no-unsafe-type-assertion\n const body = (parsed.program as unknown as SyntaxNode).body!\n // oxlint-enable typescript/no-unsafe-type-assertion\n const exported = body.find((node) => node.type === 'ExportDefaultDeclaration')?.declaration\n if (!exported) throw new Error('[nuxt-files-sdk:invalid-config] files.config.ts needs a default export.')\n let root = unwrap(exported)\n if (root.type === 'CallExpression') root = unwrap(root.arguments?.[0] ?? root)\n if (root.type === 'Identifier') {\n const declaration = body.flatMap((node) => node.declarations ?? []).find((node) => node.id?.name === root.name)\n if (declaration?.init) root = unwrap(declaration.init)\n }\n if (root.type !== 'ObjectExpression') {\n throw new Error('[nuxt-files-sdk:invalid-config] The default Files config must be a static object literal.')\n }\n const edits: Array<{ start: number; end: number; text: string }> = []\n const active = new Set(environments)\n for (const property of root.properties ?? []) {\n const key = keyOf(property)\n if (!key?.startsWith('$')) continue\n if (key === '$env' && property.value) {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const env = unwrap(property.value as SyntaxNode)\n if (env.type !== 'ObjectExpression')\n throw new Error('[nuxt-files-sdk:invalid-config] $env must be an object.')\n for (const entry of env.properties ?? []) {\n if (!active.has(keyOf(entry) ?? '')) edits.push({ start: entry.start, end: entry.end, text: '...{}' })\n }\n } else if (!active.has(key.slice(1))) {\n edits.push({ start: property.start, end: property.end, text: '...{}' })\n }\n }\n // The selected module lives under the build directory; preserve relative import resolution.\n for (const node of body) {\n if (!node.source || typeof node.source.value !== 'string' || !node.source.value.startsWith('.')) continue\n edits.push({\n start: node.source.start,\n end: node.source.end,\n text: JSON.stringify(resolve(dirname(configPath), node.source.value).replaceAll('\\\\', '/')),\n })\n }\n let result = source\n for (const edit of edits.toSorted((left, right) => right.start - left.start)) {\n result = result.slice(0, edit.start) + edit.text + result.slice(edit.end)\n }\n return result\n}\n"],"mappings":";;;AAuBA,MAAM,UAAU,SACZ,KAAK,SAAS,oBAAoB,KAAK,SAAS,2BAA2B,KAAK,SAAS,4BACnF,OAAO,KAAK,UAAW,IACvB;AACV,MAAM,SAAS,SACX,KAAK,KAAK,SAAS,eAAe,KAAK,IAAI,OAAO,OAAO,KAAK,KAAK,UAAU,WAAW,KAAK,IAAI,QAAQ,KAAA;;AAG7G,MAAa,0BAA0B,QAAgB,YAAoB,iBAA4C;CACnH,MAAM,SAAS,UAAU,YAAY,QAAQ;EAAE,YAAY;EAAU,MAAM;CAAK,CAAC;CACjF,IAAI,OAAO,OAAO,SAAS,GACvB,MAAM,IAAI,MAAM,mCAAmC,OAAO,OAAO,EAAE,CAAE,SAAS;CAIlF,MAAM,OAAQ,OAAO,QAAkC;CAEvD,MAAM,WAAW,KAAK,MAAM,SAAS,KAAK,SAAS,0BAA0B,CAAC,EAAE;CAChF,IAAI,CAAC,UAAU,MAAM,IAAI,MAAM,yEAAyE;CACxG,IAAI,OAAO,OAAO,QAAQ;CAC1B,IAAI,KAAK,SAAS,kBAAkB,OAAO,OAAO,KAAK,YAAY,MAAM,IAAI;CAC7E,IAAI,KAAK,SA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,MAAM,QAAQ,MAAM,UAAU,MAAM,UAAU,MAAM,QAAQ,KAAK,KAAK,GACvE,SAAS,OAAO,MAAM,GAAG,KAAK,KAAK,IAAI,KAAK,OAAO,OAAO,MAAM,KAAK,GAAG;CAE5E,OAAO;AACX"}
|
|
@@ -139,7 +139,7 @@ const setupNitroFilesIntegration = async (nitro, options) => {
|
|
|
139
139
|
}
|
|
140
140
|
nitro.unimport?.getInternalContext().addons.push({
|
|
141
141
|
name: "nuxt-files-sdk-jsdoc",
|
|
142
|
-
declaration: (declarations) => declarations.replace(/^([ \t]*)const (useServerFiles|syncFiles|transferFiles): typeof .*\.\2$/gmu, (_, indent, name) => `${name === "useServerFiles" ? `${indent}/** Return the project's Files client, including its configured plugin extensions. */\n` : ""}${indent}const ${name}: typeof import('nuxt-files-sdk
|
|
142
|
+
declaration: (declarations) => declarations.replace(/^([ \t]*)const (defineFilesConfig|useServerFiles|syncFiles|transferFiles): typeof .*\.\2$/gmu, (_, indent, name) => `${name === "useServerFiles" ? `${indent}/** Return the project's Files client, including its configured plugin extensions. */\n` : ""}${indent}const ${name}: typeof import('nuxt-files-sdk/${name === "defineFilesConfig" ? "config" : "runtime"}').${name}`)
|
|
143
143
|
});
|
|
144
144
|
const externals = nitro.options.externals ??= {};
|
|
145
145
|
(externals.inline ??= []).push("nuxt-files-sdk");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nitro.js","names":[],"sources":["../../src/integration/nitro.ts"],"sourcesContent":["import { mkdir, readFile, writeFile } from 'node:fs/promises'\nimport { createRequire } from 'node:module'\nimport { resolve } from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nimport type { ProviderSlug } from 'files-sdk'\nimport { getProvider, listEnvVars } from 'files-sdk/providers'\n\nimport { loadFilesConfig } from '../config/load'\nimport { pruneFilesConfigSource } from '../config/prune'\nimport { normalizeFilesConfig } from '../runtime/normalize'\n\nexport interface NitroIntegration {\n meta?: { majorVersion?: number }\n options: {\n rootDir: string\n buildDir: string\n dev?: boolean\n static?: boolean\n preset?: string\n plugins: string[]\n handlers?: { route: string; handler: string }[]\n alias?: Record<string, string>\n externals?: { inline?: unknown[] }\n }\n unimport?: {\n injectImports(code: string, id?: string): Promise<{ code: string }>\n getInternalContext(): {\n addons: {\n name?: string\n declaration?: (declarations: string) => string\n }[]\n }\n }\n hooks: {\n hook(\n name: 'types:extend',\n callback: (types: {\n tsConfig?: {\n include?: string[]\n compilerOptions?: { paths?: Record<string, string[]> }\n }\n }) => void | Promise<void>,\n ): void\n }\n}\n\nexport interface NitroFilesIntegrationOptions {\n configPath: string\n environments: readonly string[]\n}\n\nconst AWS_CORE_DEPENDENCIES = [\n '@aws-sdk/client-s3',\n '@aws-sdk/s3-presigned-post',\n '@aws-sdk/s3-request-presigner',\n] as const\nconst AWS_MULTIPART_DEPENDENCY = '@aws-sdk/lib-storage'\nconst FETCH_CAPABLE_S3_ADAPTERS = new Set<ProviderSlug>(['minio', 'r2', 'rustfs'])\nconst WORKERD_PRESETS = new Set(['cloudflare-module', 'cloudflare-durable', 'cloudflare-pages'])\n\nexport const optionalAwsSdkDependencies = (\n adapters: ProviderSlug[],\n options: { nitroMajor: number; preset?: string | undefined; resolvable: (dependency: string) => boolean },\n): string[] => {\n if (options.nitroMajor >= 3 || !options.preset || !WORKERD_PRESETS.has(options.preset)) return []\n const s3Adapters = adapters.filter((adapter) => getProvider(adapter)?.peerDeps.includes('@aws-sdk/client-s3'))\n if (s3Adapters.length === 0) return []\n const optional = s3Adapters.every((adapter) => FETCH_CAPABLE_S3_ADAPTERS.has(adapter))\n ? [...AWS_CORE_DEPENDENCIES, AWS_MULTIPART_DEPENDENCY]\n : [AWS_MULTIPART_DEPENDENCY]\n return optional.filter((dependency) => !options.resolvable(dependency))\n}\n\nconst nitroMajorVersion = (nitro: NitroIntegration): number => nitro.meta?.majorVersion ?? ('routing' in nitro ? 3 : 2)\n\nexport const selectedAdapters = (config: unknown): { adapters: ProviderSlug[]; single: boolean } => {\n const entries = normalizeFilesConfig(config)\n const single = entries.has(undefined)\n const adapters = [\n ...new Set(\n [...entries.values()]\n .map(({ storage }) => storage.adapter)\n .filter((adapter): adapter is ProviderSlug => typeof adapter === 'string'),\n ),\n ].toSorted()\n for (const adapter of adapters) {\n if (!getProvider(adapter)) {\n throw new Error(`[nuxt-files-sdk:unknown-adapter] Unknown adapter \"${adapter}\".`)\n }\n }\n return { adapters, single }\n}\n\nexport const gatewayRoutes = (config: unknown): { path: string; storage?: string }[] => {\n const routes = config && typeof config === 'object' && 'routes' in config ? config.routes : undefined\n if (routes === undefined) return []\n if (!Array.isArray(routes)) throw new Error('[nuxt-files-sdk:invalid-route] routes must be an array.')\n const storages = normalizeFilesConfig(config)\n const paths = new Set<string>()\n const selected: { path: string; storage?: string }[] = []\n for (const route of routes as unknown[]) {\n if (\n !route ||\n typeof route !== 'object' ||\n !('path' in route) ||\n typeof route.path !== 'string' ||\n !/^\\/(?:[\\w.~-]+(?:\\/[\\w.~-]+)*)?$/u.test(route.path)\n ) {\n throw new Error('[nuxt-files-sdk:invalid-route] Each route needs a static absolute path.')\n }\n if (paths.has(route.path)) throw new Error(`[nuxt-files-sdk:duplicate-route] Duplicate route \"${route.path}\".`)\n paths.add(route.path)\n const name = 'storage' in route ? route.storage : undefined\n if (storages.has(undefined) ? name !== undefined : typeof name !== 'string' || !storages.has(name)) {\n throw new Error(`[nuxt-files-sdk:unknown-storage] Invalid storage for route \"${route.path}\".`)\n }\n selected.push(typeof name === 'string' ? { path: route.path, storage: name } : { path: route.path })\n }\n return selected\n}\n\nconst factoryName = (adapter: ProviderSlug): string =>\n adapter === 'cloudinary'\n ? 'cloudinaryAdapter'\n : adapter.replaceAll(/-([a-z0-9])/gu, (_, character: string) => character.toUpperCase())\n\nexport const providerCode = (adapters: ProviderSlug[]): { imports: string; factories: string } => ({\n imports: adapters\n .map(\n (adapter, index) =>\n `import { ${factoryName(adapter)} as provider${index} } from ${JSON.stringify(`files-sdk/${adapter}`)}`,\n )\n .join('\\n'),\n factories: adapters.map((adapter, index) => `${JSON.stringify(adapter)}: provider${index}`).join(', '),\n})\n\nconst hookTypes = (moduleName: 'nitropack/types' | 'nitro/types'): string => `\ndeclare module ${JSON.stringify(moduleName)} {\n interface NitroRuntimeHooks {\n 'files:action': (payload: { event: import('files-sdk').FilesActionEvent; storage?: string }) => void | Promise<void>\n 'files:error': (payload: { event: import('files-sdk').FilesErrorEvent; storage?: string }) => void | Promise<void>\n 'files:retry': (payload: { event: import('files-sdk').FilesRetryEvent; storage?: string }) => void | Promise<void>\n }\n}\n`\n\nexport const storageTypes = (\n configPath: string,\n nitroMajor: number,\n): string => `import type config from ${JSON.stringify(configPath)}\nimport type { SingleStorage, StorageRegistry } from 'nuxt-files-sdk/runtime'\n\ndeclare module 'nuxt-files-sdk/runtime' {\n interface NuxtFilesSingleStorage { value: SingleStorage<typeof config> }\n interface NuxtFilesStorageRegistry extends StorageRegistry<typeof config> {}\n}\n${hookTypes(nitroMajor >= 3 ? 'nitro/types' : 'nitropack/types')}\nexport {}\n`\n\nexport const setupNitroFilesIntegration = async (\n nitro: NitroIntegration,\n options: NitroFilesIntegrationOptions,\n): Promise<boolean> => {\n const configPath = options.configPath.replaceAll('\\\\', '/')\n const config = await loadFilesConfig({\n configPath,\n environments: options.environments,\n alias: nitro.options.alias,\n injectImports: nitro.unimport?.injectImports.bind(nitro.unimport),\n })\n if (!config) return false\n const selected = selectedAdapters(config)\n const directory = resolve(nitro.options.rootDir, nitro.options.buildDir, 'nuxt-files-sdk')\n const typesPath = resolve(directory, 'storage-registry.d.ts')\n let writeRuntime: (() => Promise<void>) | undefined\n const writeTypes = async (): Promise<void> => {\n await mkdir(directory, { recursive: true })\n await writeFile(typesPath, storageTypes(configPath, nitroMajorVersion(nitro)))\n }\n await writeTypes()\n nitro.hooks.hook('types:extend', async (types) => {\n await writeTypes()\n await writeRuntime?.()\n const tsConfig = (types.tsConfig ??= {})\n ;(tsConfig.include ??= []).push(typesPath)\n const paths = ((tsConfig.compilerOptions ??= {}).paths ??= {})\n paths['files-sdk'] ??= [resolve(nitro.options.rootDir, 'node_modules/files-sdk').replaceAll('\\\\', '/')]\n })\n const routes = gatewayRoutes(config)\n const { adapters } = selected\n const providers = providerCode(adapters)\n const internalPath = fileURLToPath(new URL('../runtime/internal.js', import.meta.url)).replaceAll('\\\\', '/')\n const environment = Object.fromEntries(\n adapters.map((adapter) => [\n adapter,\n listEnvVars(adapter)\n .filter((variable) => variable.readBy === 'files-sdk')\n .map((variable) => [variable.key, ...(variable.aliases ?? [])]),\n ]),\n )\n const require = createRequire(resolve(nitro.options.rootDir, 'package.json'))\n const aliases = nitro.options.alias ?? {}\n const awsShims = optionalAwsSdkDependencies(adapters, {\n nitroMajor: nitroMajorVersion(nitro),\n preset: nitro.options.preset,\n resolvable: (dependency) => {\n if (Object.hasOwn(aliases, dependency)) return true\n try {\n require.resolve(dependency)\n return true\n } catch {\n return false\n }\n },\n })\n const shimFiles = awsShims.map((dependency) => ({\n dependency,\n path: resolve(directory, `${dependency.replaceAll(/[^a-z0-9]+/giu, '-')}.mjs`),\n }))\n if (shimFiles.length > 0) {\n nitro.options.alias = aliases\n for (const { dependency, path } of shimFiles) aliases[dependency] = path.replaceAll('\\\\', '/')\n }\n nitro.unimport?.getInternalContext().addons.push({\n name: 'nuxt-files-sdk-jsdoc',\n declaration: (declarations) =>\n declarations.replace(\n /^([ \\t]*)const (useServerFiles|syncFiles|transferFiles): typeof .*\\.\\2$/gmu,\n (_, indent: string, name: string) =>\n `${name === 'useServerFiles' ? `${indent}/** Return the project's Files client, including its configured plugin extensions. */\\n` : ''}${indent}const ${name}: typeof import('nuxt-files-sdk/runtime').${name}`,\n ),\n })\n // Inline both packages so installed consumers also tree-shake the plugin barrel.\n const externals = (nitro.options.externals ??= {})\n ;(externals.inline ??= []).push('nuxt-files-sdk')\n // Nitro's single-file dev build would eagerly import every native provider SDK.\n if (!nitro.options.dev) externals.inline.push('files-sdk')\n const pluginPath = resolve(directory, nitro.options.dev ? 'plugin.dev.mjs' : 'plugin.mjs')\n const resolvedPath = resolve(directory, nitro.options.dev ? 'resolved.dev.mjs' : 'resolved.mjs')\n const selectedPath = resolve(directory, nitro.options.dev ? 'selected.dev.ts' : 'selected.ts')\n const routePaths = routes.map((_, index) =>\n resolve(directory, `gateway-${index}${nitro.options.dev ? '.dev' : ''}.mjs`).replaceAll('\\\\', '/'),\n )\n for (const [index, route] of routes.entries()) {\n ;(nitro.options.handlers ??= []).push({ route: route.path, handler: routePaths[index]! })\n }\n // Development also externalizes local .mjs files unless explicitly inlined.\n externals.inline.push(\n pluginPath.replaceAll('\\\\', '/'),\n resolvedPath.replaceAll('\\\\', '/'),\n selectedPath.replaceAll('\\\\', '/'),\n ...routePaths,\n )\n nitro.options.plugins.push(pluginPath.replaceAll('\\\\', '/'))\n writeRuntime = async (): Promise<void> => {\n await mkdir(directory, { recursive: true })\n await Promise.all(\n shimFiles.map(({ dependency, path }) =>\n writeFile(\n path,\n `throw new Error(${JSON.stringify(`[nuxt-files-sdk:missing-optional-dependency] ${dependency} is required for this Files SDK operation. Install it or select the provider's fetch client.`)})\\n`,\n ),\n ),\n )\n const originalSource = await readFile(configPath, 'utf8')\n const importedSource = nitro.unimport\n ? (await nitro.unimport.injectImports(originalSource, configPath)).code\n : originalSource\n await writeFile(selectedPath, pruneFilesConfigSource(importedSource, configPath, options.environments))\n const mergePath = fileURLToPath(new URL('../config/merge.js', import.meta.url)).replaceAll('\\\\', '/')\n const selectedBranches = options.environments\n .flatMap((name) => [`raw[${JSON.stringify(`$${name}`)}]`, `raw.$env?.[${JSON.stringify(name)}]`])\n .toReversed()\n await writeFile(\n resolvedPath,\n `import raw from ${JSON.stringify(selectedPath.replaceAll('\\\\', '/'))}\\nimport { mergeFilesConfig } from ${JSON.stringify(mergePath)}\\nconst resolved = mergeFilesConfig(${[...selectedBranches, 'raw'].join(', ')})\\nexport default { storage: resolved.storage, routes: resolved.routes }\\n`,\n )\n await writeFile(\n pluginPath,\n `import config from ${JSON.stringify(resolvedPath.replaceAll('\\\\', '/'))}\n${providers.imports}\nimport { configureFiles } from ${JSON.stringify(internalPath)}\n\nexport default (nitroApp) => configureFiles(config, {\n factories: { ${providers.factories} },\n environment: ${JSON.stringify(environment)},\n hooks: {\n onAction: (event, storage) => nitroApp.hooks.callHook('files:action', { event, storage }),\n onError: (event, storage) => nitroApp.hooks.callHook('files:error', { event, storage }),\n onRetry: (event, storage) => nitroApp.hooks.callHook('files:retry', { event, storage }),\n },\n})\n`,\n )\n await Promise.all(\n routePaths.map((path, index) => {\n const route = routes[index]!\n const handler =\n nitroMajorVersion(nitro) >= 3 ? 'router.handle(event.req)' : 'createRouteHandler(router)(event)'\n return writeFile(\n path,\n `import config from ${JSON.stringify(resolvedPath.replaceAll('\\\\', '/'))}\nimport { createFilesRouter } from 'files-sdk/api'\n${nitroMajorVersion(nitro) >= 3 ? '' : \"import { createRouteHandler } from 'files-sdk/nitro'\"}\nimport { getFiles } from ${JSON.stringify(internalPath)}\n\nconst route = config.routes[${index}]\nconst environmentSecret = typeof process === 'undefined' ? undefined : process.env?.FILES_API_SECRET\nconst secret = route.authorize\n ? route.secret || environmentSecret || crypto.randomUUID() + crypto.randomUUID()\n : route.secret\nif (route.authorize && !route.secret && !environmentSecret) {\n console.warn('[nuxt-files-sdk:gateway-secret] Set FILES_API_SECRET for upload tokens shared across processes.')\n}\nlet sharedRouter\nconst makeRouter = (event) => createFilesRouter({\n ...route,\n files: () => getFiles(${route.storage === undefined ? '' : JSON.stringify(route.storage)}),\n secret,\n authorize: route.authorize && ((context) => route.authorize({ ...context, event })),\n})\nexport default (event) => {\n const router = route.authorize ? makeRouter(event) : (sharedRouter ??= makeRouter(event))\n return ${handler}\n}\n`,\n )\n }),\n )\n }\n await writeRuntime()\n return true\n}\n"],"mappings":";;;;;;;;;AAoDA,MAAM,wBAAwB;CAC1B;CACA;CACA;AACJ;AACA,MAAM,2BAA2B;AACjC,MAAM,4CAA4B,IAAI,IAAkB;CAA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F,cACA,mBAAmB,KAAK,UAAU,aAAa,WAAW,MAAM,GAAG,CAAC,EAAE,qCAAqC,KAAK,UAAU,SAAS,EAAE,sCAAsC,CAAC,GAAG,kBAAkB,KAAK,CAAC,CAAC,KAAK,IAAI,EAAE,2EACvN;EACA,MAAM,UACF,YACA,sBAAsB,KAAK,UAAU,aAAa,WAAW,MAAM,GAAG,CAAC,EAAE;EACnF,UAAU,QAAQ;iCACa,KAAK,UAAU,YAAY,EAAE;;;iBAG7C,UAAU,UAAU;iBACpB,KAAK,UAAU,WAAW,EAAE;;;;;;;CAQrC;EACA,MAAM,QAAQ,IACV,WAAW,KAAK,MAAM,UAAU;GAC5B,MAAM,QAAQ,OAAO;GACrB,MAAM,UACF,kBAAkB,KAAK,KAAK,IAAI,6BAA6B;GACjE,OAAO,UACH,MACA,sBAAsB,KAAK,UAAU,aAAa,WAAW,MAAM,GAAG,CAAC,EAAE;;EAE3F,kBAAkB,KAAK,KAAK,IAAI,KAAK,uDAAuD;2BACnE,KAAK,UAAU,YAAY,EAAE;;8BAE1B,MAAM;;;;;;;;;;;0BAWV,MAAM,YAAY,KAAA,IAAY,KAAK,KAAK,UAAU,MAAM,OAAO,EAAE;;;;;;WAMhF,QAAQ;;CAGH;EACJ,CAAC,CACL;CACJ;CACA,MAAM,aAAa;CACnB,OAAO;AACX"}
|
|
1
|
+
{"version":3,"file":"nitro.js","names":[],"sources":["../../src/integration/nitro.ts"],"sourcesContent":["import { mkdir, readFile, writeFile } from 'node:fs/promises'\nimport { createRequire } from 'node:module'\nimport { resolve } from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nimport type { ProviderSlug } from 'files-sdk'\nimport { getProvider, listEnvVars } from 'files-sdk/providers'\n\nimport { loadFilesConfig } from '../config/load'\nimport { pruneFilesConfigSource } from '../config/prune'\nimport { normalizeFilesConfig } from '../runtime/normalize'\n\nexport interface NitroIntegration {\n meta?: { majorVersion?: number }\n options: {\n rootDir: string\n buildDir: string\n dev?: boolean\n static?: boolean\n preset?: string\n plugins: string[]\n handlers?: { route: string; handler: string }[]\n alias?: Record<string, string>\n externals?: { inline?: unknown[] }\n }\n unimport?: {\n injectImports(code: string, id?: string): Promise<{ code: string }>\n getInternalContext(): {\n addons: {\n name?: string\n declaration?: (declarations: string) => string\n }[]\n }\n }\n hooks: {\n hook(\n name: 'types:extend',\n callback: (types: {\n tsConfig?: {\n include?: string[]\n compilerOptions?: { paths?: Record<string, string[]> }\n }\n }) => void | Promise<void>,\n ): void\n }\n}\n\nexport interface NitroFilesIntegrationOptions {\n configPath: string\n environments: readonly string[]\n}\n\nconst AWS_CORE_DEPENDENCIES = [\n '@aws-sdk/client-s3',\n '@aws-sdk/s3-presigned-post',\n '@aws-sdk/s3-request-presigner',\n] as const\nconst AWS_MULTIPART_DEPENDENCY = '@aws-sdk/lib-storage'\nconst FETCH_CAPABLE_S3_ADAPTERS = new Set<ProviderSlug>(['minio', 'r2', 'rustfs'])\nconst WORKERD_PRESETS = new Set(['cloudflare-module', 'cloudflare-durable', 'cloudflare-pages'])\n\nexport const optionalAwsSdkDependencies = (\n adapters: ProviderSlug[],\n options: { nitroMajor: number; preset?: string | undefined; resolvable: (dependency: string) => boolean },\n): string[] => {\n if (options.nitroMajor >= 3 || !options.preset || !WORKERD_PRESETS.has(options.preset)) return []\n const s3Adapters = adapters.filter((adapter) => getProvider(adapter)?.peerDeps.includes('@aws-sdk/client-s3'))\n if (s3Adapters.length === 0) return []\n const optional = s3Adapters.every((adapter) => FETCH_CAPABLE_S3_ADAPTERS.has(adapter))\n ? [...AWS_CORE_DEPENDENCIES, AWS_MULTIPART_DEPENDENCY]\n : [AWS_MULTIPART_DEPENDENCY]\n return optional.filter((dependency) => !options.resolvable(dependency))\n}\n\nconst nitroMajorVersion = (nitro: NitroIntegration): number => nitro.meta?.majorVersion ?? ('routing' in nitro ? 3 : 2)\n\nexport const selectedAdapters = (config: unknown): { adapters: ProviderSlug[]; single: boolean } => {\n const entries = normalizeFilesConfig(config)\n const single = entries.has(undefined)\n const adapters = [\n ...new Set(\n [...entries.values()]\n .map(({ storage }) => storage.adapter)\n .filter((adapter): adapter is ProviderSlug => typeof adapter === 'string'),\n ),\n ].toSorted()\n for (const adapter of adapters) {\n if (!getProvider(adapter)) {\n throw new Error(`[nuxt-files-sdk:unknown-adapter] Unknown adapter \"${adapter}\".`)\n }\n }\n return { adapters, single }\n}\n\nexport const gatewayRoutes = (config: unknown): { path: string; storage?: string }[] => {\n const routes = config && typeof config === 'object' && 'routes' in config ? config.routes : undefined\n if (routes === undefined) return []\n if (!Array.isArray(routes)) throw new Error('[nuxt-files-sdk:invalid-route] routes must be an array.')\n const storages = normalizeFilesConfig(config)\n const paths = new Set<string>()\n const selected: { path: string; storage?: string }[] = []\n for (const route of routes as unknown[]) {\n if (\n !route ||\n typeof route !== 'object' ||\n !('path' in route) ||\n typeof route.path !== 'string' ||\n !/^\\/(?:[\\w.~-]+(?:\\/[\\w.~-]+)*)?$/u.test(route.path)\n ) {\n throw new Error('[nuxt-files-sdk:invalid-route] Each route needs a static absolute path.')\n }\n if (paths.has(route.path)) throw new Error(`[nuxt-files-sdk:duplicate-route] Duplicate route \"${route.path}\".`)\n paths.add(route.path)\n const name = 'storage' in route ? route.storage : undefined\n if (storages.has(undefined) ? name !== undefined : typeof name !== 'string' || !storages.has(name)) {\n throw new Error(`[nuxt-files-sdk:unknown-storage] Invalid storage for route \"${route.path}\".`)\n }\n selected.push(typeof name === 'string' ? { path: route.path, storage: name } : { path: route.path })\n }\n return selected\n}\n\nconst factoryName = (adapter: ProviderSlug): string =>\n adapter === 'cloudinary'\n ? 'cloudinaryAdapter'\n : adapter.replaceAll(/-([a-z0-9])/gu, (_, character: string) => character.toUpperCase())\n\nexport const providerCode = (adapters: ProviderSlug[]): { imports: string; factories: string } => ({\n imports: adapters\n .map(\n (adapter, index) =>\n `import { ${factoryName(adapter)} as provider${index} } from ${JSON.stringify(`files-sdk/${adapter}`)}`,\n )\n .join('\\n'),\n factories: adapters.map((adapter, index) => `${JSON.stringify(adapter)}: provider${index}`).join(', '),\n})\n\nconst hookTypes = (moduleName: 'nitropack/types' | 'nitro/types'): string => `\ndeclare module ${JSON.stringify(moduleName)} {\n interface NitroRuntimeHooks {\n 'files:action': (payload: { event: import('files-sdk').FilesActionEvent; storage?: string }) => void | Promise<void>\n 'files:error': (payload: { event: import('files-sdk').FilesErrorEvent; storage?: string }) => void | Promise<void>\n 'files:retry': (payload: { event: import('files-sdk').FilesRetryEvent; storage?: string }) => void | Promise<void>\n }\n}\n`\n\nexport const storageTypes = (\n configPath: string,\n nitroMajor: number,\n): string => `import type config from ${JSON.stringify(configPath)}\nimport type { SingleStorage, StorageRegistry } from 'nuxt-files-sdk/runtime'\n\ndeclare module 'nuxt-files-sdk/runtime' {\n interface NuxtFilesSingleStorage { value: SingleStorage<typeof config> }\n interface NuxtFilesStorageRegistry extends StorageRegistry<typeof config> {}\n}\n${hookTypes(nitroMajor >= 3 ? 'nitro/types' : 'nitropack/types')}\nexport {}\n`\n\nexport const setupNitroFilesIntegration = async (\n nitro: NitroIntegration,\n options: NitroFilesIntegrationOptions,\n): Promise<boolean> => {\n const configPath = options.configPath.replaceAll('\\\\', '/')\n const config = await loadFilesConfig({\n configPath,\n environments: options.environments,\n alias: nitro.options.alias,\n injectImports: nitro.unimport?.injectImports.bind(nitro.unimport),\n })\n if (!config) return false\n const selected = selectedAdapters(config)\n const directory = resolve(nitro.options.rootDir, nitro.options.buildDir, 'nuxt-files-sdk')\n const typesPath = resolve(directory, 'storage-registry.d.ts')\n let writeRuntime: (() => Promise<void>) | undefined\n const writeTypes = async (): Promise<void> => {\n await mkdir(directory, { recursive: true })\n await writeFile(typesPath, storageTypes(configPath, nitroMajorVersion(nitro)))\n }\n await writeTypes()\n nitro.hooks.hook('types:extend', async (types) => {\n await writeTypes()\n await writeRuntime?.()\n const tsConfig = (types.tsConfig ??= {})\n ;(tsConfig.include ??= []).push(typesPath)\n const paths = ((tsConfig.compilerOptions ??= {}).paths ??= {})\n paths['files-sdk'] ??= [resolve(nitro.options.rootDir, 'node_modules/files-sdk').replaceAll('\\\\', '/')]\n })\n const routes = gatewayRoutes(config)\n const { adapters } = selected\n const providers = providerCode(adapters)\n const internalPath = fileURLToPath(new URL('../runtime/internal.js', import.meta.url)).replaceAll('\\\\', '/')\n const environment = Object.fromEntries(\n adapters.map((adapter) => [\n adapter,\n listEnvVars(adapter)\n .filter((variable) => variable.readBy === 'files-sdk')\n .map((variable) => [variable.key, ...(variable.aliases ?? [])]),\n ]),\n )\n const require = createRequire(resolve(nitro.options.rootDir, 'package.json'))\n const aliases = nitro.options.alias ?? {}\n const awsShims = optionalAwsSdkDependencies(adapters, {\n nitroMajor: nitroMajorVersion(nitro),\n preset: nitro.options.preset,\n resolvable: (dependency) => {\n if (Object.hasOwn(aliases, dependency)) return true\n try {\n require.resolve(dependency)\n return true\n } catch {\n return false\n }\n },\n })\n const shimFiles = awsShims.map((dependency) => ({\n dependency,\n path: resolve(directory, `${dependency.replaceAll(/[^a-z0-9]+/giu, '-')}.mjs`),\n }))\n if (shimFiles.length > 0) {\n nitro.options.alias = aliases\n for (const { dependency, path } of shimFiles) aliases[dependency] = path.replaceAll('\\\\', '/')\n }\n nitro.unimport?.getInternalContext().addons.push({\n name: 'nuxt-files-sdk-jsdoc',\n declaration: (declarations) =>\n declarations.replace(\n /^([ \\t]*)const (defineFilesConfig|useServerFiles|syncFiles|transferFiles): typeof .*\\.\\2$/gmu,\n (_, indent: string, name: string) =>\n `${name === 'useServerFiles' ? `${indent}/** Return the project's Files client, including its configured plugin extensions. */\\n` : ''}${indent}const ${name}: typeof import('nuxt-files-sdk/${name === 'defineFilesConfig' ? 'config' : 'runtime'}').${name}`,\n ),\n })\n // Inline both packages so installed consumers also tree-shake the plugin barrel.\n const externals = (nitro.options.externals ??= {})\n ;(externals.inline ??= []).push('nuxt-files-sdk')\n // Nitro's single-file dev build would eagerly import every native provider SDK.\n if (!nitro.options.dev) externals.inline.push('files-sdk')\n const pluginPath = resolve(directory, nitro.options.dev ? 'plugin.dev.mjs' : 'plugin.mjs')\n const resolvedPath = resolve(directory, nitro.options.dev ? 'resolved.dev.mjs' : 'resolved.mjs')\n const selectedPath = resolve(directory, nitro.options.dev ? 'selected.dev.ts' : 'selected.ts')\n const routePaths = routes.map((_, index) =>\n resolve(directory, `gateway-${index}${nitro.options.dev ? '.dev' : ''}.mjs`).replaceAll('\\\\', '/'),\n )\n for (const [index, route] of routes.entries()) {\n ;(nitro.options.handlers ??= []).push({ route: route.path, handler: routePaths[index]! })\n }\n // Development also externalizes local .mjs files unless explicitly inlined.\n externals.inline.push(\n pluginPath.replaceAll('\\\\', '/'),\n resolvedPath.replaceAll('\\\\', '/'),\n selectedPath.replaceAll('\\\\', '/'),\n ...routePaths,\n )\n nitro.options.plugins.push(pluginPath.replaceAll('\\\\', '/'))\n writeRuntime = async (): Promise<void> => {\n await mkdir(directory, { recursive: true })\n await Promise.all(\n shimFiles.map(({ dependency, path }) =>\n writeFile(\n path,\n `throw new Error(${JSON.stringify(`[nuxt-files-sdk:missing-optional-dependency] ${dependency} is required for this Files SDK operation. Install it or select the provider's fetch client.`)})\\n`,\n ),\n ),\n )\n const originalSource = await readFile(configPath, 'utf8')\n const importedSource = nitro.unimport\n ? (await nitro.unimport.injectImports(originalSource, configPath)).code\n : originalSource\n await writeFile(selectedPath, pruneFilesConfigSource(importedSource, configPath, options.environments))\n const mergePath = fileURLToPath(new URL('../config/merge.js', import.meta.url)).replaceAll('\\\\', '/')\n const selectedBranches = options.environments\n .flatMap((name) => [`raw[${JSON.stringify(`$${name}`)}]`, `raw.$env?.[${JSON.stringify(name)}]`])\n .toReversed()\n await writeFile(\n resolvedPath,\n `import raw from ${JSON.stringify(selectedPath.replaceAll('\\\\', '/'))}\\nimport { mergeFilesConfig } from ${JSON.stringify(mergePath)}\\nconst resolved = mergeFilesConfig(${[...selectedBranches, 'raw'].join(', ')})\\nexport default { storage: resolved.storage, routes: resolved.routes }\\n`,\n )\n await writeFile(\n pluginPath,\n `import config from ${JSON.stringify(resolvedPath.replaceAll('\\\\', '/'))}\n${providers.imports}\nimport { configureFiles } from ${JSON.stringify(internalPath)}\n\nexport default (nitroApp) => configureFiles(config, {\n factories: { ${providers.factories} },\n environment: ${JSON.stringify(environment)},\n hooks: {\n onAction: (event, storage) => nitroApp.hooks.callHook('files:action', { event, storage }),\n onError: (event, storage) => nitroApp.hooks.callHook('files:error', { event, storage }),\n onRetry: (event, storage) => nitroApp.hooks.callHook('files:retry', { event, storage }),\n },\n})\n`,\n )\n await Promise.all(\n routePaths.map((path, index) => {\n const route = routes[index]!\n const handler =\n nitroMajorVersion(nitro) >= 3 ? 'router.handle(event.req)' : 'createRouteHandler(router)(event)'\n return writeFile(\n path,\n `import config from ${JSON.stringify(resolvedPath.replaceAll('\\\\', '/'))}\nimport { createFilesRouter } from 'files-sdk/api'\n${nitroMajorVersion(nitro) >= 3 ? '' : \"import { createRouteHandler } from 'files-sdk/nitro'\"}\nimport { getFiles } from ${JSON.stringify(internalPath)}\n\nconst route = config.routes[${index}]\nconst environmentSecret = typeof process === 'undefined' ? undefined : process.env?.FILES_API_SECRET\nconst secret = route.authorize\n ? route.secret || environmentSecret || crypto.randomUUID() + crypto.randomUUID()\n : route.secret\nif (route.authorize && !route.secret && !environmentSecret) {\n console.warn('[nuxt-files-sdk:gateway-secret] Set FILES_API_SECRET for upload tokens shared across processes.')\n}\nlet sharedRouter\nconst makeRouter = (event) => createFilesRouter({\n ...route,\n files: () => getFiles(${route.storage === undefined ? '' : JSON.stringify(route.storage)}),\n secret,\n authorize: route.authorize && ((context) => route.authorize({ ...context, event })),\n})\nexport default (event) => {\n const router = route.authorize ? makeRouter(event) : (sharedRouter ??= makeRouter(event))\n return ${handler}\n}\n`,\n )\n }),\n )\n }\n await writeRuntime()\n return true\n}\n"],"mappings":";;;;;;;;;AAoDA,MAAM,wBAAwB;CAC1B;CACA;CACA;AACJ;AACA,MAAM,2BAA2B;AACjC,MAAM,4CAA4B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,EAAE,EAAE,CAAC,CAAC,CAChG,WAAW;EAChB,MAAM,UACF,cACA,mBAAmB,KAAK,UAAU,aAAa,WAAW,MAAM,GAAG,CAAC,EAAE,qCAAqC,KAAK,UAAU,SAAS,EAAE,sCAAsC,CAAC,GAAG,kBAAkB,KAAK,CAAC,CAAC,KAAK,IAAI,EAAE,2EACvN;EACA,MAAM,UACF,YACA,sBAAsB,KAAK,UAAU,aAAa,WAAW,MAAM,GAAG,CAAC,EAAE;EACnF,UAAU,QAAQ;iCACa,KAAK,UAAU,YAAY,EAAE;;;iBAG7C,UAAU,UAAU;iBACpB,KAAK,UAAU,WAAW,EAAE;;;;;;;CAQrC;EACA,MAAM,QAAQ,IACV,WAAW,KAAK,MAAM,UAAU;GAC5B,MAAM,QAAQ,OAAO;GACrB,MAAM,UACF,kBAAkB,KAAK,KAAK,IAAI,6BAA6B;GACjE,OAAO,UACH,MACA,sBAAsB,KAAK,UAAU,aAAa,WAAW,MAAM,GAAG,CAAC,EAAE;;EAE3F,kBAAkB,KAAK,KAAK,IAAI,KAAK,uDAAuD;2BACnE,KAAK,UAAU,YAAY,EAAE;;8BAE1B,MAAM;;;;;;;;;;;0BAWV,MAAM,YAAY,KAAA,IAAY,KAAK,KAAK,UAAU,MAAM,OAAO,EAAE;;;;;;WAMhF,QAAQ;;CAGH;EACJ,CAAC,CACL;CACJ;CACA,MAAM,aAAa;CACnB,OAAO;AACX"}
|
package/dist/package.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nuxt-files-sdk",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"description": "Files SDK integration for Nuxt with DevTools",
|
|
5
5
|
"homepage": "https://nuxt-files-sdk.liria.me",
|
|
6
6
|
"license": "MIT",
|
|
@@ -49,12 +49,12 @@
|
|
|
49
49
|
"typecheck": "tsc --noEmit"
|
|
50
50
|
},
|
|
51
51
|
"dependencies": {
|
|
52
|
-
"@babel/parser": "^7.29.9",
|
|
53
52
|
"@nuxt/devtools-kit": "4.0.0-beta.2",
|
|
54
53
|
"@nuxt/kit": "^4.5.2",
|
|
55
54
|
"c12": "^3.3.4",
|
|
56
55
|
"devframe": "^1.1.0",
|
|
57
|
-
"jiti": "^2.7.0"
|
|
56
|
+
"jiti": "^2.7.0",
|
|
57
|
+
"oxc-parser": "^0.150.0"
|
|
58
58
|
},
|
|
59
59
|
"devDependencies": {
|
|
60
60
|
"@arethetypeswrong/cli": "^0.18.5",
|